def view_init(self, cr, uid, fields_list, context=None):
     """
      Creates view dynamically and adding fields at runtime.
      @param self: The object pointer.
      @param cr: A database cursor
      @param uid: ID of the user currently logged in
      @param context: A standard dictionary
      @return: New arch of view with new columns.
     """
     res = super(AccountBalanceCommonWizard, self).view_init(cr, uid, fields_list, context=context)
     for index in range(self.COMPARISON_LEVEL):
         # create columns for each comparison page
         self._columns.update({
             "comp%s_filter" % (index,):
                 fields.selection(self.COMPARE_SELECTION,
                                  string="Compare By",
                                  required=True),
             "comp%s_fiscalyear_id" % (index,):
                 fields.many2one('account.fiscalyear', 'Fiscal year'),
             "comp%s_period_from" % (index,):
                 fields.many2one('account.period', 'Start period'),
             "comp%s_period_to" % (index,):
                 fields.many2one('account.period', 'End period'),
             "comp%s_date_from" % (index,):
                 fields.date("Start Date"),
             "comp%s_date_to" % (index,):
                 fields.date("End Date"),
         })
     return res
 def 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.
     """
     if context is None:
         context = {}
     res = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context)
     record_id = context and context.get('active_id', False)
     if record_id:
         pick_obj = self.pool.get('stock.picking')
         pick = pick_obj.browse(cr, uid, record_id, context=context)
         if pick.state not in ['done','confirmed','assigned']:
             raise osv.except_osv(_('Warning !'), _("You may only return pickings that are Confirmed, Available or Done!"))
         return_history = {}
         valid_lines = 0
         for m in [line for line in pick.move_lines]:
             if m.state == 'done':
                 return_history[m.id] = 0
                 for rec in m.move_history_ids2:
                     return_history[m.id] += (rec.product_qty * rec.product_uom.factor)
                 if m.product_qty * m.product_uom.factor >= return_history[m.id]:
                     valid_lines += 1
                     if 'return%s'%(m.id) not in self._columns:
                         self._columns['return%s'%(m.id)] = fields.float(string=m.name, required=True)
                     if 'invoice_state' not in self._columns:
                         self._columns['invoice_state'] = fields.selection([('2binvoiced', 'To be refunded/invoiced'), ('none', 'No invoicing')], string='Invoicing', required=True)
         if not valid_lines:
             raise osv.except_osv(_('Warning !'), _("There are no products to return (only lines in Done state and not fully returned yet can be returned)!"))
     return res
    def _build_form(self, cr, uid, field_datas, value1, value2):
        formxml = '''<?xml version="1.0"?>
            <form string="%s">
            <separator colspan="4" string="Select datas for new record"/>''' % _('Merge')
        update_values = {}
        update_fields = {}
        columns = {}

        for fid, fname, fdescription, ttype, required, relation, readonly in field_datas:
            val1 = value1[fname]
            val2 = value2[fname]
            my_selection = []
            size = 24

            if (val1 and val2) and (val1 == val2):
                if ttype in ('many2one'):
                    update_values.update({fname: val1.id})
                elif ttype in ('many2many'):
                    update_values.update({fname: [(6, 0, map(lambda x: x.id, val1))]})
                else:
                    update_values.update({fname: val1})

            if (val1 and val2) and (val1 != val2) and not readonly:
                if ttype in ('char', 'text', 'selection'):
                    my_selection = [(val1, val1), (val2, val2)]
                    size = max(len(val1), len(val2))
                if ttype in ('float', 'integer'):
                    my_selection = [(str(val1), str(val1)), (str(val2), str(val2))]
                if ttype in ('many2one'):
                    my_selection = [(str(val1.id), val1.name),
                                    (str(val2.id), val2.name)]
                if ttype in ('many2many'):
                    update_values.update({fname: [(6, 0, list(set(map(lambda x: x.id, val1 + val2))))]})
                if my_selection:
                    if not required:
                        my_selection.append((False, ''))
                    columns.update({fname: fields.selection(my_selection, fdescription, required=required, size=size)})
                    update_fields.update({fname: {'string': fdescription, 'type': 'selection', 'selection': my_selection, 'required': required}})
                    formxml += '\n<field name="%s"/><newline/>' % (fname,)
            if (val1 and not val2) or (not val1 and val2):
                if ttype == 'many2one':
                    update_values.update({fname: val1 and val1.id or val2 and val2.id})
                elif ttype == 'many2many':
                    update_values.update({fname: [(6, 0, map(lambda x: x.id, val1 or val2))]})
                elif ttype == 'one2many':
                    #skip one2many values
                    pass
                else:
                    update_values.update({fname: val1 or val2})

        formxml += """
        <separator colspan="4"/>
        <group col="4" colspan="4">
            <label string="" colspan="2"/>
            <button special="cancel" string="Cancel" icon="gtk-cancel"/>
            <button name="action_merge" string="Merge" type="object" icon="gtk-ok"/>
        </group>
        </form>"""
        return formxml, update_fields, update_values, columns
class drugs_recreational(osv.osv):
    _name = "medical.drugs_recreational"
    _columns = {
        'name':
        fields.char('Name', size=128, help="Name of the drug"),
        'street_name':
        fields.char('Street names',
                    size=256,
                    help="Common name of the drug in street jargon"),
        'toxicity':
        fields.selection([
            ('0', 'None'),
            ('1', 'Low'),
            ('2', 'High'),
            ('3', 'Extreme'),
        ],
                         'Toxicity',
                         select=True),
        'addiction_level':
        fields.selection([
            ('0', 'None'),
            ('1', 'Low'),
            ('2', 'High'),
            ('3', 'Extreme'),
        ],
                         'Dependence',
                         select=True),
        'legal_status':
        fields.selection([
            ('0', 'Legal'),
            ('1', 'Illegal'),
        ],
                         'Legal Status',
                         select=True),
        'category':
        fields.selection([
            ('cannabinoid', 'Cannabinoids'),
            ('depressant', 'Depressants'),
            ('dissociative', 'Dissociative Anesthetics'),
            ('hallucinogen', 'Hallucinogens'),
            ('opioid', 'Opioids'),
            ('stimulant', 'Stimulants'),
            ('other', 'Others'),
        ],
                         'Category',
                         select=True),
        'withdrawal_level':
        fields.integer(
            "Withdrawal",
            help=
            "Presence and severity ofcharacteristic withdrawal symptoms.\nUsing Henningfield rating. 1=highest and 6=lowest"
        ),
        'reinforcement_level':
        fields.integer(
            "Reinforcement",
            help=
            "A measure of the substance's ability to get users to take it again and again, and in preference to other substances.\nUsing Henningfield rating. 1=highest and 6=lowest"
        ),
        'tolerance_level':
        fields.integer(
            "Tolerance",
            help=
            "How much of the substance is needed to satisfy increasing cravings for it, and the level of stable need that is eventually reached.\nUsing Henningfield rating. 1=highest and 6=lowest"
        ),
        'dependence_level':
        fields.integer(
            "Dependence",
            help=
            "How difficult it is for the user to quit, the relapse rate, the percentage of people who eventually become dependent, the rating users give their own need for the substance and the degree to which the substance will be used in the face of evidence that it causes harm.\nUsing Henningfield rating. 1=highest and 6=lowest"
        ),
        'intoxication_level':
        fields.integer(
            "Intoxication",
            help=
            "the level of intoxication is associated with addiction and increases the personal and social damage a substance may do. \nUsing Henningfield rating. 1=highest and 6=lowest"
        ),
        'route_oral':
        fields.boolean('Oral', help=""),
        'route_popping':
        fields.boolean('Skin Popping',
                       help="Subcutaneous or Intradermical administration"),
        'route_inhaling':
        fields.boolean('Smoke / Inhale', help="Insufflation, exluding nasal"),
        'route_sniffing':
        fields.boolean(
            'Sniffing',
            help="Also called snorting - inhaling through the nares  "),
        'route_injection':
        fields.boolean('Injection',
                       help="Injection - Intravenous, Intramuscular..."),
        'dea_schedule_i':
        fields.boolean(
            'DEA schedule I',
            help=
            "Schedule I and II drugs have a high potential for abuse. They require greater storage security and have a quota on manufacturing, among other restrictions. Schedule I drugs are available for research only and have no approved medical use; Schedule II drugs are available only by prescription (unrefillable) and require a form for ordering. Schedule III and IV drugs are available by prescription, may have five refills in 6 months, and may be ordered orally. Some Schedule V drugs are available over the counter"
        ),
        'dea_schedule_ii':
        fields.boolean(
            'II',
            help=
            "Schedule I and II drugs have a high potential for abuse. They require greater storage security and have a quota on manufacturing, among other restrictions. Schedule I drugs are available for research only and have no approved medical use; Schedule II drugs are available only by prescription (unrefillable) and require a form for ordering. Schedule III and IV drugs are available by prescription, may have five refills in 6 months, and may be ordered orally. Some Schedule V drugs are available over the counter"
        ),
        'dea_schedule_iii':
        fields.boolean(
            'III',
            help=
            "Schedule I and II drugs have a high potential for abuse. They require greater storage security and have a quota on manufacturing, among other restrictions. Schedule I drugs are available for research only and have no approved medical use; Schedule II drugs are available only by prescription (unrefillable) and require a form for ordering. Schedule III and IV drugs are available by prescription, may have five refills in 6 months, and may be ordered orally. Some Schedule V drugs are available over the counter"
        ),
        'dea_schedule_iv':
        fields.boolean(
            'IV',
            help=
            "Schedule I and II drugs have a high potential for abuse. They require greater storage security and have a quota on manufacturing, among other restrictions. Schedule I drugs are available for research only and have no approved medical use; Schedule II drugs are available only by prescription (unrefillable) and require a form for ordering. Schedule III and IV drugs are available by prescription, may have five refills in 6 months, and may be ordered orally. Some Schedule V drugs are available over the counter"
        ),
        'dea_schedule_v':
        fields.boolean(
            'V',
            help=
            "Schedule I and II drugs have a high potential for abuse. They require greater storage security and have a quota on manufacturing, among other restrictions. Schedule I drugs are available for research only and have no approved medical use; Schedule II drugs are available only by prescription (unrefillable) and require a form for ordering. Schedule III and IV drugs are available by prescription, may have five refills in 6 months, and may be ordered orally. Some Schedule V drugs are available over the counter"
        ),
        'info':
        fields.text('Extra Info'),
    }
Пример #5
0
                     'product_id' : ids[0],
                     'amazon_product_attributes' : data
                 }
             amazon_prod_master_obj = self.pool.get('amazon.products.master')
             amazon_prod_master_id  = amazon_prod_master_obj.create(cr,uid,prodvals)
     else:
              raise osv.except_osv(_('Warning !'),'No products found on Amazon as per your search query. Please try again')
     return True
 _columns = {
     'amazon_sku': fields.char('Amazon SKU', size=126),
     'amazon_asin': fields.char('ASIN', size=16,readonly=True),
     'orderitemid': fields.char('Orderitemid', size=16),
     'product_order_item_id': fields.char('Order_item_id', size=256),
     'amazon_export':fields.boolean('Exported to Amazon'),
     'amazon_category':fields.many2one('amazon.category','Amazon Category'),
     'amz_type': fields.selection([('',''),('IBSN','IBSN'),('UPC','UPC'),('EAN','EAN'),('ASIN','ASIN')],'Type'),
     'amz_type_value': fields.char('Amazon Type Value', size=126),
     'amzn_condtn': fields.selection([('',''),('New','New'),('UsedLikeNew','Used Like New'),('UsedVeryGood','Used Very Good'),('UsedGood','UsedGood')
     ,('UsedAcceptable','Used Acceptable'),('CollectibleLikeNew','Collectible Like New'),('CollectibleVeryGood','Collectible Very Good'),('CollectibleGood','Collectible Good')
     ,('CollectibleAcceptable','Collectible Acceptable'),('Refurbished','Refurbished'),('Club','Club')],'Amazon Condition'),
     'prod_query': fields.char('Product Search Query', size=200, help="A search string with the same support as that is provided on Amazon marketplace websites."),
     'prod_query_contextid': fields.selection(_amazon_browse_node_get,'Query ContextId', help="An identifier for the context within which the given search will be performed."),
     'amazon_instance_id': fields.selection(_amazon_instance_get,'Amazon Instance', help="Select the Amazon instance where you want to perform search."),
     'amazon_products_ids': fields.one2many('amazon.products.master', 'product_id', 'Amazon Searched Products'),
     'amazon_prod_status':  fields.selection([('active','Active'),('fail','Failure')],'Status',readonly="True"),
     'operation_performed': fields.char('Operation Performed', size=126),
     'submit_feed_result' : fields.text('Submit Feed Result',readonly=True),
     'amazon_updated_price':fields.float('Amazon Updated Price',digits=(16,2)),
     'condition_note' : fields.text('Condition Note'),
 }
 _defaults = {
Пример #6
0
        'year':fields.many2one('mttl.years', 'Year', required=True, help="Year of model"),
        'location':fields.many2one('mttl.locations', 'Location', required=True, help="Manufacture location"),
        'country':fields.many2one('mttl.countries', 'Country', required=True, help="Country of manufacture"),
        'chassis':fields.many2one('mttl.chassis', 'Chassis', required=True, help="Who supplied the chassis, or was it sold as a kit?"),
        'partner_id':fields.many2one('res.partner', 'Customer', change_default=True, help="Last known owner of this unit", domain="[('customer','=',True)]"),
        'dealer_id':fields.many2one('res.partner', 'Dealer', change_default=True, help="Last known owner of this unit", domain="[('dealer','=',True)]"),
        'destination_id':fields.many2one('res.partner', 'Destination', change_default=True, help="Last known location of this unit", domain="[('customer','=',True)]"),
        'serial_number':fields.char('Serial Number',size=17, required=True, help="The Computed Serial Number.  Verify that no periods or question marks are present"),
        
        #Vehicle Information
        'chassis_weight': fields.char("Chassis Weight", size=10, help="Weight of Chassis without Wrecker"),
        'wrecker_weight': fields.char("Wrecker Weight", size=10, help="Weight of Wrecker without Chassis"),
        'installed_weight':fields.char("Installed Weight", size=10, help="Completed Vehicle Weight including accessories and fluids"),
        'vehicle_model':fields.many2one("mttl.vehicle.model",'Model', help="Chassis Model"),
        'vehicle_make':fields.many2one('mttl.vehicle.make','Make', help="Chassis Make"),
        'vehicle_year':fields.selection(_get_vehicle_year(),'Year', help="Chassis Year"),
        'vehicle_vin':fields.char('Vehicle VIN', size=20),
        '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"),
        google = self.pool.get('google.login')
        res = []
        try:
            gd_client = google.google_login(user_obj.gmail_user, user_obj.gmail_password, type='calendar')
            calendars = gd_client.GetAllCalendarsFeed()
            for cal in calendars.entry:
                res.append((cal.id.text, cal.title.text))
        except Exception, e:
            return [('failed', 'Connection to google fail')]
        res.append(('all', 'All Calendars'))
        return res

    _columns = {
        'customer': fields.boolean('Customer', help="Check this box to set newly created partner as Customer."),
        'supplier': fields.boolean('Supplier', help="Check this box to set newly created partner as Supplier."),
        'group_name': fields.selection(_get_group, "Group Name",help="Choose which group to import, By default it takes all."),
        'calendar_name': fields.selection(_get_calendars, "Calendar Name"),
     }

    _defaults = {
        'group_name': 'all',
    }

    def import_google(self, cr, uid, ids, context=None):
        if context == None:
            context = {}
        if not ids:
            return {'type': 'ir.actions.act_window_close'}
        obj = self.browse(cr, uid, ids, context=context)[0]
        cust = obj.customer
        sup = obj.supplier
Пример #8
0
 '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
 #Lets plan it for 0.9
 'folder':fields.selection([
                 ('inbox', 'Inbox'),
                 ('drafts', 'Drafts'),
                 ('outbox', 'Outbox'),
                 ('trash', 'Trash'),
                 ('followup', 'Follow Up'),
                 ('sent', 'Sent Items'),
                 ], 'Folder', required=True),
Пример #9
0
            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),
        
    }

    def default_get(self, cr, uid, fields, context=None):
        config_obj = self.pool.get('oo.config')
        data = super(aeroo_config_installer, self).default_get(cr, uid, fields, context=context)
        ids = config_obj.search(cr, 1, [], context=context)
        if ids:
            res = config_obj.read(cr, 1, ids[0], context=context)
Пример #10
0
class crm_lead_report_assign(osv.osv):
    """ CRM Lead Report """
    _name = "crm.lead.report.assign"
    _auto = False
    _description = "CRM Lead Report"
    _columns = {
        'year': fields.char('Year', size=64, required=False, readonly=True),
        'partner_assigned_id':fields.many2one('res.partner', 'Partner', readonly=True),
        'grade_id':fields.many2one('res.partner.grade', 'Grade', readonly=True),
        'user_id':fields.many2one('res.users', 'User', readonly=True),
        'country_id':fields.many2one('res.country', 'Country', readonly=True),
        'section_id':fields.many2one('crm.case.section', 'Sales 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),
        'date_assign': fields.date('Partner Date', readonly=True),
        'create_date': fields.datetime('Create Date', readonly=True),
        'day': fields.char('Day', size=128, readonly=True),
        'delay_open': fields.float('Delay to Open',digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to open the case"),
        'delay_close': fields.float('Delay to Close',digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to close the case"),
        'delay_expected': fields.float('Overpassed Deadline',digits=(16,2),readonly=True, group_operator="avg"),
        'probability': fields.float('Avg Probability',digits=(16,2),readonly=True, group_operator="avg"),
        'probability_max': fields.float('Max Probability',digits=(16,2),readonly=True, group_operator="max"),
        'planned_revenue': fields.float('Planned Revenue',digits=(16,2),readonly=True),
        'probable_revenue': fields.float('Probable Revenue', digits=(16,2),readonly=True),
        'categ_id': fields.many2one('crm.case.categ', 'Category',\
                         domain="[('section_id','=',section_id)]" , readonly=True),
        'stage_id': fields.many2one ('crm.case.stage', 'Stage', domain="[('section_ids', '=', section_id)]"),
        'partner_id': fields.many2one('res.partner', 'Customer' , readonly=True),
        'opening_date': fields.date('Opening Date', readonly=True),
        'creation_date': fields.date('Creation Date', readonly=True),
        'date_closed': fields.date('Close Date', readonly=True),
        'nbr': fields.integer('# of Cases', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', readonly=True),
        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
        'type':fields.selection([
            ('lead','Lead'),
            ('opportunity','Opportunity'),
        ],'Type', help="Type is used to separate Leads and Opportunities"),
    }

    def init(self, cr):
        """
            CRM Lead Report
            @param cr: the current row, from the database cursor
        """
        tools.drop_view_if_exists(cr, 'crm_lead_report_assign')
        cr.execute("""
            CREATE OR REPLACE VIEW crm_lead_report_assign AS (
                SELECT
                    c.id,
                    to_char(c.date_assign, 'YYYY') as year,
                    to_char(c.date_assign, 'MM') as month,
                    to_char(c.date_assign, 'YYYY-MM-DD') as day,
                    to_char(c.create_date, 'YYYY-MM-DD') as creation_date,
                    to_char(c.date_open, 'YYYY-MM-DD') as opening_date,
                    to_char(c.date_closed, 'YYYY-mm-dd') as date_closed,
                    c.state,
                    c.date_assign,
                    c.user_id,
                    c.probability,
                    c.probability as probability_max,
                    c.stage_id,
                    c.type,
                    c.company_id,
                    c.priority,
                    c.section_id,
                    c.categ_id,
                    c.partner_id,
                    c.country_id,
                    c.planned_revenue,
                    c.partner_assigned_id,
                    p.grade_id,
                    p.date as partner_date,
                    c.planned_revenue*(c.probability/100) as probable_revenue, 
                    1 as nbr,
                    date_trunc('day',c.create_date) as create_date,
                    extract('epoch' from (c.date_closed-c.create_date))/(3600*24) as  delay_close,
                    extract('epoch' from (c.date_deadline - c.date_closed))/(3600*24) as  delay_expected,
                    extract('epoch' from (c.date_open-c.create_date))/(3600*24) as  delay_open
                FROM
                    crm_lead c
                    left join res_partner p on (c.partner_assigned_id=p.id)
            )""")
Пример #11
0
class product_product(osv.osv):
    _inherit = "product.product"

    def get_product_accounts(self, cr, uid, product_id, context=None):
        """ To get the stock input account, stock output account and stock journal related to product.
        @param product_id: product id
        @return: dictionary which contains information regarding stock input account, stock output account and stock journal
        """
        if context is None:
            context = {}
        product_obj = self.pool.get('product.product').browse(cr, uid, product_id, context=context)

        stock_input_acc = product_obj.property_stock_account_input and product_obj.property_stock_account_input.id or False
        if not stock_input_acc:
            stock_input_acc = product_obj.categ_id.property_stock_account_input_categ and product_obj.categ_id.property_stock_account_input_categ.id or False

        stock_output_acc = product_obj.property_stock_account_output and product_obj.property_stock_account_output.id or False
        if not stock_output_acc:
            stock_output_acc = product_obj.categ_id.property_stock_account_output_categ and product_obj.categ_id.property_stock_account_output_categ.id or False

        journal_id = product_obj.categ_id.property_stock_journal and product_obj.categ_id.property_stock_journal.id or False
        account_valuation = product_obj.categ_id.property_stock_valuation_account_id and product_obj.categ_id.property_stock_valuation_account_id.id or False
        return {
            'stock_account_input': stock_input_acc,
            'stock_account_output': stock_output_acc,
            'stock_journal': journal_id,
            'property_stock_valuation_account_id': account_valuation
        }

    def do_change_standard_price(self, cr, uid, ids, datas, context=None):
        """ Changes the Standard Price of Product and creates an account move accordingly.
        @param datas : dict. contain default datas like new_price, stock_output_account, stock_input_account, stock_journal
        @param context: A standard dictionary
        @return:

        """
        location_obj = self.pool.get('stock.location')
        move_obj = self.pool.get('account.move')
        move_line_obj = self.pool.get('account.move.line')
        if context is None:
            context = {}

        new_price = datas.get('new_price', 0.0)
        stock_output_acc = datas.get('stock_output_account', False)
        stock_input_acc = datas.get('stock_input_account', False)
        journal_id = datas.get('stock_journal', False)
        product_obj=self.browse(cr, uid, ids, context=context)[0]
        account_valuation = product_obj.categ_id.property_stock_valuation_account_id
        account_valuation_id = account_valuation and account_valuation.id or False
        if not account_valuation_id: raise osv.except_osv(_('Error!'), _('Valuation Account is not specified for Product Category: %s') % (product_obj.categ_id.name))
        move_ids = []
        loc_ids = location_obj.search(cr, uid,[('usage','=','internal')])
        for rec_id in ids:
            for location in location_obj.browse(cr, uid, loc_ids, context=context):
                c = context.copy()
                c.update({
                    'location': location.id,
                    'compute_child': False
                })

                product = self.browse(cr, uid, rec_id, context=c)
                qty = product.qty_available
                diff = product.standard_price - new_price
                if not diff: raise osv.except_osv(_('Error!'), _("Could not find any difference between standard price and new price!"))
                if qty:
                    company_id = location.company_id and location.company_id.id or False
                    if not company_id: raise osv.except_osv(_('Error!'), _('Company is not specified in Location'))
                    #
                    # Accounting Entries
                    #
                    if not journal_id:
                        journal_id = product.categ_id.property_stock_journal and product.categ_id.property_stock_journal.id or False
                    if not journal_id:
                        raise osv.except_osv(_('Error!'),
                            _('There is no journal defined '\
                                'on the product category: "%s" (id: %d)') % \
                                (product.categ_id.name,
                                    product.categ_id.id,))
                    move_id = move_obj.create(cr, uid, {
                                'journal_id': journal_id,
                                'company_id': company_id
                                })

                    move_ids.append(move_id)


                    if diff > 0:
                        if not stock_input_acc:
                            stock_input_acc = product.product_tmpl_id.\
                                property_stock_account_input.id
                        if not stock_input_acc:
                            stock_input_acc = product.categ_id.\
                                    property_stock_account_input_categ.id
                        if not stock_input_acc:
                            raise osv.except_osv(_('Error!'),
                                    _('There is no stock input account defined ' \
                                            'for this product: "%s" (id: %d)') % \
                                            (product.name,
                                                product.id,))
                        amount_diff = qty * diff
                        move_line_obj.create(cr, uid, {
                                    'name': product.name,
                                    'account_id': stock_input_acc,
                                    'debit': amount_diff,
                                    'move_id': move_id,
                                    })
                        move_line_obj.create(cr, uid, {
                                    'name': product.categ_id.name,
                                    'account_id': account_valuation_id,
                                    'credit': amount_diff,
                                    'move_id': move_id
                                    })
                    elif diff < 0:
                        if not stock_output_acc:
                            stock_output_acc = product.product_tmpl_id.\
                                property_stock_account_output.id
                        if not stock_output_acc:
                            stock_output_acc = product.categ_id.\
                                    property_stock_account_output_categ.id
                        if not stock_output_acc:
                            raise osv.except_osv(_('Error!'),
                                    _('There is no stock output account defined ' \
                                            'for this product: "%s" (id: %d)') % \
                                            (product.name,
                                                product.id,))
                        amount_diff = qty * -diff
                        move_line_obj.create(cr, uid, {
                                        'name': product.name,
                                        'account_id': stock_output_acc,
                                        'credit': amount_diff,
                                        'move_id': move_id
                                    })
                        move_line_obj.create(cr, uid, {
                                        'name': product.categ_id.name,
                                        'account_id': account_valuation_id,
                                        'debit': amount_diff,
                                        'move_id': move_id
                                    })

            self.write(cr, uid, rec_id, {'standard_price': new_price})

        return move_ids

    def view_header_get(self, cr, user, view_id, view_type, context=None):
        if context is None:
            context = {}
        res = super(product_product, self).view_header_get(cr, user, view_id, view_type, context)
        if res: return res
        if (context.get('active_id', False)) and (context.get('active_model') == 'stock.location'):
            return _('Products: ')+self.pool.get('stock.location').browse(cr, user, context['active_id'], context).name
        return res

    def get_product_available(self, cr, uid, ids, context=None):
        """ Finds whether product is available or not in particular warehouse.
        @return: Dictionary of values
        """
        if context is None:
            context = {}
        
        location_obj = self.pool.get('stock.location')
        warehouse_obj = self.pool.get('stock.warehouse')
        shop_obj = self.pool.get('sale.shop')
        
        states = context.get('states',[])
        what = context.get('what',())
        if not ids:
            ids = self.search(cr, uid, [])
        res = {}.fromkeys(ids, 0.0)
        if not ids:
            return res

        if context.get('shop', False):
            warehouse_id = shop_obj.read(cr, uid, int(context['shop']), ['warehouse_id'])['warehouse_id'][0]
            if warehouse_id:
                context['warehouse'] = warehouse_id

        if context.get('warehouse', False):
            lot_id = warehouse_obj.read(cr, uid, int(context['warehouse']), ['lot_stock_id'])['lot_stock_id'][0]
            if lot_id:
                context['location'] = lot_id

        if context.get('location', False):
            if type(context['location']) == type(1):
                location_ids = [context['location']]
            elif type(context['location']) in (type(''), type(u'')):
                location_ids = location_obj.search(cr, uid, [('name','ilike',context['location'])], context=context)
            else:
                location_ids = context['location']
        else:
            location_ids = []
            wids = warehouse_obj.search(cr, uid, [], context=context)
            for w in warehouse_obj.browse(cr, uid, wids, context=context):
                location_ids.append(w.lot_stock_id.id)

        # build the list of ids of children of the location given by id
        if context.get('compute_child',True):
            child_location_ids = location_obj.search(cr, uid, [('location_id', 'child_of', location_ids)])
            location_ids = child_location_ids or location_ids
        
        # this will be a dictionary of the UoM resources we need for conversion purposes, by UoM id
        uoms_o = {}
        # this will be a dictionary of the product UoM by product id
        product2uom = {}
        for product in self.browse(cr, uid, ids, context=context):
            product2uom[product.id] = product.uom_id.id
            uoms_o[product.uom_id.id] = product.uom_id

        results = []
        results2 = []

        from_date = context.get('from_date',False)
        to_date = context.get('to_date',False)
        date_str = False
        date_values = False
        where = [tuple(location_ids),tuple(location_ids),tuple(ids),tuple(states)]
        if from_date and to_date:
            date_str = "date>=%s and date<=%s"
            where.append(tuple([from_date]))
            where.append(tuple([to_date]))
        elif from_date:
            date_str = "date>=%s"
            date_values = [from_date]
        elif to_date:
            date_str = "date<=%s"
            date_values = [to_date]

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

    # TODO: perhaps merge in one query.
        if date_values:
            where.append(tuple(date_values))
        if 'in' in what:
            # all moves from a location out of the set to a location in the set
            cr.execute(
                'select sum(product_qty), product_id, product_uom '\
                'from stock_move '\
                'where location_id NOT IN %s '\
                'and location_dest_id IN %s '\
                'and product_id IN %s '\
                '' + (prodlot_id and ('and prodlot_id = ' + str(prodlot_id)) or '') + ' '\
                'and state IN %s ' + (date_str and 'and '+date_str+' ' or '') +' '\
                'group by product_id,product_uom',tuple(where))
            results = cr.fetchall()
        if 'out' in what:
            # all moves from a location in the set to a location out of the set
            cr.execute(
                'select sum(product_qty), product_id, product_uom '\
                'from stock_move '\
                'where location_id IN %s '\
                'and location_dest_id NOT IN %s '\
                'and product_id  IN %s '\
                '' + (prodlot_id and ('and prodlot_id = ' + str(prodlot_id)) or '') + ' '\
                'and state in %s ' + (date_str and 'and '+date_str+' ' or '') + ' '\
                'group by product_id,product_uom',tuple(where))
            results2 = cr.fetchall()
            
        # Get the missing UoM resources
        uom_obj = self.pool.get('product.uom')
        uoms = map(lambda x: x[2], results) + map(lambda x: x[2], results2)
        if context.get('uom', False):
            uoms += [context['uom']]
        uoms = filter(lambda x: x not in uoms_o.keys(), uoms)
        if uoms:
            uoms = uom_obj.browse(cr, uid, list(set(uoms)), context=context)
            for o in uoms:
                uoms_o[o.id] = o
                
        #TOCHECK: before change uom of product, stock move line are in old uom.
        context.update({'raise-exception': False})
        # Count the incoming quantities
        for amount, prod_id, prod_uom in results:
            amount = uom_obj._compute_qty_obj(cr, uid, uoms_o[prod_uom], amount,
                     uoms_o[context.get('uom', False) or product2uom[prod_id]], context=context)
            res[prod_id] += amount
        # Count the outgoing quantities
        for amount, prod_id, prod_uom in results2:
            amount = uom_obj._compute_qty_obj(cr, uid, uoms_o[prod_uom], amount,
                    uoms_o[context.get('uom', False) or product2uom[prod_id]], context=context)
            res[prod_id] -= amount
        return res

    def _product_available(self, cr, uid, ids, field_names=None, arg=False, context=None):
        """ Finds the incoming and outgoing quantity of product.
        @return: Dictionary of values
        """
        if not field_names:
            field_names = []
        if context is None:
            context = {}
        res = {}
        for id in ids:
            res[id] = {}.fromkeys(field_names, 0.0)
        for f in field_names:
            c = context.copy()
            if f == 'qty_available':
                c.update({ 'states': ('done',), 'what': ('in', 'out') })
            if f == 'virtual_available':
                c.update({ 'states': ('confirmed','waiting','assigned','done'), 'what': ('in', 'out') })
            if f == 'incoming_qty':
                c.update({ 'states': ('confirmed','waiting','assigned'), 'what': ('in',) })
            if f == 'outgoing_qty':
                c.update({ 'states': ('confirmed','waiting','assigned'), 'what': ('out',) })
            stock = self.get_product_available(cr, uid, ids, context=c)
            for id in ids:
                res[id][f] = stock.get(id, 0.0)
        return res

    _columns = {
        'qty_available': fields.function(_product_available, multi='qty_available',
            type='float',  digits_compute=dp.get_precision('Product UoM'),
            string='Quantity On Hand',
            help="Current quantity of products.\n"
                 "In a context with a single Stock Location, this includes "
                 "goods stored at this Location, or any of its children.\n"
                 "In a context with a single Warehouse, this includes "
                 "goods stored in the Stock Location of this Warehouse, or any "
                 "of its children.\n"
                 "In a context with a single Shop, this includes goods "
                 "stored in the Stock Location of the Warehouse of this Shop, "
                 "or any of its children.\n"
                 "Otherwise, this includes goods stored in any Stock Location "
                 "typed as 'internal'."),
        'virtual_available': fields.function(_product_available, multi='qty_available',
            type='float',  digits_compute=dp.get_precision('Product UoM'),
            string='Quantity Available',
            help="Forecast quantity (computed as Quantity On Hand "
                 "- Outgoing + Incoming)\n"
                 "In a context with a single Stock Location, this includes "
                 "goods stored at this Location, or any of its children.\n"
                 "In a context with a single Warehouse, this includes "
                 "goods stored in the Stock Location of this Warehouse, or any "
                 "of its children.\n"
                 "In a context with a single Shop, this includes goods "
                 "stored in the Stock Location of the Warehouse of this Shop, "
                 "or any of its children.\n"
                 "Otherwise, this includes goods stored in any Stock Location "
                 "typed as 'internal'."),
        'incoming_qty': fields.function(_product_available, multi='qty_available',
            type='float',  digits_compute=dp.get_precision('Product UoM'),
            string='Incoming',
            help="Quantity of products that are planned to arrive.\n"
                 "In a context with a single Stock Location, this includes "
                 "goods arriving to this Location, or any of its children.\n"
                 "In a context with a single Warehouse, this includes "
                 "goods arriving to the Stock Location of this Warehouse, or "
                 "any of its children.\n"
                 "In a context with a single Shop, this includes goods "
                 "arriving to the Stock Location of the Warehouse of this "
                 "Shop, or any of its children.\n"
                 "Otherwise, this includes goods arriving to any Stock "
                 "Location typed as 'internal'."),
        'outgoing_qty': fields.function(_product_available, multi='qty_available',
            type='float',  digits_compute=dp.get_precision('Product UoM'),
            string='Outgoing',
            help="Quantity of products that are planned to leave.\n"
                 "In a context with a single Stock Location, this includes "
                 "goods leaving from this Location, or any of its children.\n"
                 "In a context with a single Warehouse, this includes "
                 "goods leaving from the Stock Location of this Warehouse, or "
                 "any of its children.\n"
                 "In a context with a single Shop, this includes goods "
                 "leaving from the Stock Location of the Warehouse of this "
                 "Shop, or any of its children.\n"
                 "Otherwise, this includes goods leaving from any Stock "
                 "Location typed as 'internal'."),
        'track_production': fields.boolean('Track Manufacturing Lots', help="Forces to specify a Production Lot for all moves containing this product and generated by a Manufacturing Order"),
        'track_incoming': fields.boolean('Track Incoming Lots', help="Forces to specify a Production Lot for all moves containing this product and coming from a Supplier Location"),
        'track_outgoing': fields.boolean('Track Outgoing Lots', help="Forces to specify a Production Lot for all moves containing this product and going to a Customer Location"),
        'location_id': fields.dummy(string='Location', relation='stock.location', type='many2one'),
        'warehouse_id': fields.dummy(string='Warehouse', relation='stock.warehouse', type='many2one'),
        'valuation':fields.selection([('manual_periodic', 'Periodical (manual)'),
                                        ('real_time','Real Time (automated)'),], 'Inventory Valuation',
                                        help="If real-time valuation is enabled for a product, the system will automatically write journal entries corresponding to stock moves." \
                                             "The inventory variation account set on the product category will represent the current inventory value, and the stock input and stock output account will hold the counterpart moves for incoming and outgoing products."
                                        , required=True),
    }

    _defaults = {
        'valuation': 'manual_periodic',
    }

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        res = super(product_product,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
        if context is None:
            context = {}
        if ('location' in context) and context['location']:
            location_info = self.pool.get('stock.location').browse(cr, uid, context['location'])
            fields=res.get('fields',{})
            if fields:
                if location_info.usage == 'supplier':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future Receptions')
                    if fields.get('qty_available'):
                        res['fields']['qty_available']['string'] = _('Received Qty')

                if location_info.usage == 'internal':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future Stock')

                if location_info.usage == 'customer':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future Deliveries')
                    if fields.get('qty_available'):
                        res['fields']['qty_available']['string'] = _('Delivered Qty')

                if location_info.usage == 'inventory':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future P&L')
                    if fields.get('qty_available'):
                        res['fields']['qty_available']['string'] = _('P&L Qty')

                if location_info.usage == 'procurement':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future Qty')
                    if fields.get('qty_available'):
                        res['fields']['qty_available']['string'] = _('Unplanned Qty')

                if location_info.usage == 'production':
                    if fields.get('virtual_available'):
                        res['fields']['virtual_available']['string'] = _('Future Productions')
                    if fields.get('qty_available'):
                        res['fields']['qty_available']['string'] = _('Produced Qty')
        return res
Пример #12
0
class base_external_mapping_line(osv.osv):
    _inherit = 'base.external.mapping.line'

    def _check_mapping_line_name(self, cr, uid, ids):
        for mapping_line in self.browse(cr, uid, ids):
            if (not mapping_line.field_id) and (
                    not mapping_line.external_field):
                return False
        return True

    _columns = {
        'mapping_id':
        fields.many2one('base.external.mapping',
                        'External Mapping',
                        select=True,
                        ondelete='cascade'),
        'field_id':
        fields.many2one(
            'ir.model.fields',
            'OpenERP Field',
            select=True,
            ondelete='cascade',
            required=True,
            domain=
            "[('model_id', '=', parent.model_id),('ttype','!=','binary')]"),
        'external_field':
        fields.char('External Field', size=32, required=True),
        'type':
        fields.selection([('in_out', 'External <-> OpenERP'),
                          ('in', 'External -> OpenERP'),
                          ('out', 'External <- OpenERP')],
                         'Type',
                         required=True),
        'external_type':
        fields.selection([('str', 'String'), ('bool', 'Boolean'),
                          ('int', 'Integer'), ('float', 'Float')],
                         'External Type',
                         required=True),
        'translate':
        fields.boolean(
            'Translate',
            help=
            'Check this option to export fields with locale sufix. Example: name_es'
        ),
        'active':
        fields.boolean('Active'),
        'update':
        fields.boolean(
            'Exclude Update',
            help='When update data (write), this field is excluded'),
        'sequence':
        fields.integer(
            'Sequence',
            help="Is the order that you want for the columns field in the file"
        ),
        'in_function':
        fields.text('Import in OpenERP Mapping Python Function'),
        'out_function':
        fields.text('Export from OpenERP Mapping Python Function'),
    }

    _default = {
        'type': lambda *a: 'in_out',
        'active': 1,
    }

    _constraints = [(
        _check_mapping_line_name,
        "Error ! Invalid Mapping Line Name: Field and External Field cannot be both null",
        ['parent_id'])]

    _order = 'field_id desc'
Пример #13
0
class base_external_mapping(osv.osv):
    _name = 'base.external.mapping'
    _description = 'Base External Mapping'
    _rec_name = 'model_id'

    def get_oerp_to_external(self,
                             cr,
                             uid,
                             code,
                             ids=[],
                             context=None,
                             langs=[]):
        """From OpenERP values to External
            Search all mapping lines same code and calculated their values
            Return list with dictionary [{},{}]
            If not code or ids, return dicc blank
            @param code: name of mapping
            @param ids: ids get values
            @param many2many field: return a list with id m2m[]
        """

        res = []

        fields_relationals = ['many2one', 'one2many', 'many2many']

        if code == '' or len(ids) == 0:
            LOGGER.notifyChannel(_("Base External Mapping"), netsvc.LOG_ERROR,
                                 _("Code or ids without value"))
            return res

        dj_mappline_ids = self.search(cr, uid, [('name', '=', code)])
        if len(dj_mappline_ids) == 0:
            LOGGER.notifyChannel(_("Base External Mapping"), netsvc.LOG_ERROR,
                                 _("Mappline Code %s not found") % code)
            return res

        LOGGER.notifyChannel(_("Base External Mapping"), netsvc.LOG_INFO,
                             _("Base External Mapping call %s") % code)
        LOGGER.notifyChannel(_("Base External Mapping"), netsvc.LOG_INFO,
                             "IDS: %s" % ids)

        if not len(langs) > 0:
            langs = self.pool.get('res.lang').search(cr, uid,
                                                     [('active', '=', True)])

        dj_mappline = self.browse(cr, uid, dj_mappline_ids[0])

        dj_mappline_line_ids = self.pool.get(
            'base.external.mapping.line').search(
                cr, uid, [('mapping_id', '=', dj_mappline_ids[0]),
                          ('active', '=', True), '|', ('type', '=', 'out'),
                          ('type', '=', 'in_out')])

        mappline_rules = []
        for dj_mappline_line_id in dj_mappline_line_ids:
            mappline_rules_values = {}
            dj_mappline_line = self.pool.get(
                'base.external.mapping.line').browse(cr, uid,
                                                     dj_mappline_line_id,
                                                     context)
            if dj_mappline_line.type == 'out' or dj_mappline_line.type == 'in_out':
                mappline_rules_values[
                    'field_id'] = dj_mappline_line.field_id.name
                mappline_rules_values['translate'] = dj_mappline_line.translate
                mappline_rules_values[
                    'external_field'] = dj_mappline_line.external_field
                mappline_rules_values[
                    'out_function'] = dj_mappline_line.out_function
                mappline_rules_values[
                    'ttype'] = dj_mappline_line.field_id.ttype
            mappline_rules.append(mappline_rules_values)

        for data_id in ids:
            values_data = {}
            values_model = self.pool.get(dj_mappline.model_id.model).browse(
                cr, uid, data_id, context)

            values_data['id'] = data_id

            for mappline_rule in mappline_rules:
                field = mappline_rule['field_id']
                if mappline_rule['translate']:
                    for lang in langs:
                        language = self.pool.get('res.lang').browse(
                            cr, uid, lang)
                        if language.code != 'en_US':
                            trans = self.pool.get('ir.translation').search(
                                cr, uid,
                                [('lang', '=', language.code),
                                 ('name', '=',
                                  dj_mappline.model_id.model + ',' + field),
                                 ('res_id', '=', data_id)])
                            if len(trans) > 0:
                                translation = self.pool.get(
                                    'ir.translation').browse(
                                        cr, uid, trans[0])
                                trans_value = translation.value
                            else:
                                trans_value = getattr(values_model, field)
                                if trans_value is False:
                                    trans_value = ''
                        else:
                            trans_value = getattr(values_model, field)
                            if trans_value is False:
                                trans_value = ''
                        values_data[mappline_rule['external_field'] + '_' +
                                    language.code[:2]] = trans_value
                else:
                    if mappline_rule['out_function']:
                        localspace = {
                            "self": self,
                            "cr": cr,
                            "uid": uid,
                            "ids": ids,
                            "context": context
                        }
                        exec mappline_rule['out_function'] in localspace
                        value = localspace[
                            'value'] if 'value' in localspace else None
                    else:
                        if mappline_rule['ttype'] in fields_relationals:
                            if mappline_rule[
                                    'ttype'] == 'many2many':  #m2m fields, create list
                                value = []
                                values = getattr(values_model, field)
                                for val in values:
                                    value.append(val.id)
                            else:
                                value = getattr(values_model, field).id
                        else:
                            value = getattr(values_model, field)

                        if mappline_rule['ttype'] == 'char' and value == False:
                            value = ''

                    if mappline_rule[
                            'ttype'] == 'boolean' and value == False:  #force add this false
                        values_data[mappline_rule['external_field']] = False
                    if value:
                        values_data[mappline_rule['external_field']] = value

            res.append(values_data)

        if DEBUG:
            LOGGER.notifyChannel(_("Base External Mapping"), netsvc.LOG_INFO,
                                 _("%s") % res)

        return res

    def get_external_to_oerp(self, cr, uid, code, id, values={}, context=None):
        """
        From External values to OpenERP
        Get dicc and process values
        @param code: str
        @param id: int
        @param values: dicc
        :return vals dicc values recalculated
        """

        external_mappings = self.search(cr, uid, [('name', '=', code)])
        if not (external_mappings) > 0:
            return False

        vals = {}
        external_mapping = self.browse(cr, uid, external_mappings[0])
        for mapping_line in external_mapping.mapping_ids:
            if mapping_line.external_field in values and (
                    mapping_line.type == 'in_out' or mapping_line.type
                    == 'in') and mapping_line.active == True:
                if mapping_line.in_function:
                    localspace = {
                        "self": self,
                        "cr": cr,
                        "uid": uid,
                        "id": id,
                        "values": values[mapping_line.external_field],
                        "context": context
                    }
                    exec mapping_line.in_function in localspace
                    value = localspace['value']
                else:
                    value = values[mapping_line.external_field]
                #force type value (float, int, bool) (default is str)
                if mapping_line.external_type == 'float':
                    try:
                        value = float(value)
                    except:
                        pass
                if mapping_line.external_type == 'int':
                    try:
                        value = int(value)
                    except:
                        pass
                if mapping_line.external_type == 'bool':
                    if value == '1':
                        value = True
                    else:
                        value = False
                vals[mapping_line.field_id.name] = value

        return vals

    def exclude_uptade(self, cr, uid, code, values={}, context=None):
        """
        Exclude some values dicc (remove dicc values)
        @param code: str
        @param values: dicc
        :return vals dicc values recalculated
        """

        external_mappings = self.search(cr, uid, [('name', '=', code)])
        if not (external_mappings) > 0:
            return False

        exclude_lines = []
        for line in self.browse(cr, uid, external_mappings[0]).mapping_ids:
            if line.update:
                exclude_lines.append(line.field_id.name)

        for line in exclude_lines:
            if line in values:
                del values[line]

        return values

    _columns = {
        'name':
        fields.char('Code', size=64, required=True),
        'model_id':
        fields.many2one('ir.model',
                        'OpenERP Model',
                        required=True,
                        select=True,
                        ondelete='cascade'),
        'model':
        fields.related('model_id', 'model', type='char', string='Model Name'),
        'mapping_ids':
        fields.one2many('base.external.mapping.line', 'mapping_id',
                        'Mappings Lines'),
        'state':
        fields.selection([('draft', 'Draft'), ('done', 'Done')],
                         'State',
                         required=True,
                         readonly=True),
    }

    _defaults = {
        'state': lambda *a: 'draft',
    }

    def create(self, cr, uid, vals, context=None):
        dj_external_mapping_ids = self.pool.get(
            'base.external.mapping').search(cr, uid,
                                            [('name', 'ilike', vals['name'])])
        if len(dj_external_mapping_ids) > 0:
            raise osv.except_osv(_('Error !'),
                                 _("Another External Mapping have same code!"))
        vals['state'] = 'done'
        return super(base_external_mapping,
                     self).create(cr, uid, vals, context)
Пример #14
0
class account_budget_niss(osv.osv):
    _name = "account.budget.niss"

    _columns = {
        'number':
        fields.char('Number', size=156),
        'name':
        fields.char('Name', size=256),
        'date':
        fields.date('Date', select=True),
        'date_actual':
        fields.date('Actual Date', select=True),
        'type':
        fields.selection([('main', 'Main Budget'),
                          ('detail', 'Detail Budget')], 'Type'),
        'fiscalyear_id':
        fields.many2one('account.fiscalyear.budget', 'Year'),
        'line_ids':
        fields.one2many('account.budget.niss.line', 'budget_niss_id',
                        'Budget lines'),
        'state':
        fields.selection([('draft', 'Draft'), ('confirmed', 'Confirmed')],
                         'State',
                         readonly=True,
                         select=True),
    }

    def _get_type(self, cr, uid, context=None):
        """
        Get type of Budget
        @return : type or False 
        """
        if context is None:
            context = {}
        return context.get('type', False)

    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d'),
        'date_actual': lambda *a: time.strftime('%Y-%m-%d'),
        'state': 'draft',
        'number': '/',
        'type': _get_type,
    }

    def create(self, cr, user, vals, context=None):
        """
        Override to add constrain of sequance
        @param vals: Dictionary of values
        @return: super of exchange_order
        """
        if ('number' not in vals) or (vals.get('number') == '/'):
            seq = self.pool.get('ir.sequence').get(cr, user,
                                                   'account.budget.niss')
            vals['number'] = seq and seq or '/'
            if not seq:
                raise osv.except_osv(
                    _('Warning'),
                    _('No sequence defined!\nPleas contact administartor to configue sequence with code \'account.budget.niss\''
                      ))
        new_id = super(account_budget_niss,
                       self).create(cr, user, vals, context)
        return new_id

    def get_actual_amount(self, cr, uid, ids, context=None):
        """
        return actual amount of budget line
        """
        budget_line_obj = self.pool.get('account.budget.niss.line')
        account_obj = self.pool.get('account.account')
        if context is None:
            context = {}
        ctx = context.copy()
        for record in self.browse(cr, uid, ids, context):
            year, month, date = record.date_actual.split('-')
            ctx['date_from'] = datetime(int(year), 1, 1).strftime("%Y-%m-%d")
            ctx['date_to'] = record.date_actual
            ctx['state'] = 'all'

            for line in record.line_ids:
                if line.account_id:
                    result = account_obj.read(cr, uid, line.account_id.id,
                                              ['balance'], ctx)
                    budget_line_obj.write(
                        cr, uid, [line.id],
                        {'actual_amount': result.get('balance')}, context)
Пример #15
0
class campaign_partner(osv.osv):
    _name = "campaign.partner"
    _columns = {
        'name': fields.char('Name / Reference', size=64, required=True),
        'user_id': fields.many2one('res.users', 'Salesman'),
        'step': fields.many2one('campaign.step', 'Step', required=True, states={'wait':[('readonly',True)],'stop':[('readonly',True)]}),
        'priority': fields.selection([('0','Very Low'),('1','Low'),('2','Medium'),('3','High'),('4','Very High')], 'Priority', required=True, states={'wait':[('readonly',True)],'stop':[('readonly',True)]}),
        'partner_id': fields.many2one('res.partner', 'Partner', required=True),
        'part_adr_id': fields.many2one('res.partner.address', 'Partner Address', required=True),
        'contact': fields.char('Partner Contact', size=64),
        'notes': fields.text('Prospect Notes'),

        'date_recall': fields.datetime('Call again on', states={'wait':[('readonly',True)],'stop':[('readonly',True)]}),
        'info': fields.text('Comments', states={'wait':[('readonly',True)],'stop':[('readonly',True)]}),
        'active': fields.boolean('Active'),
        'history_ids': fields.one2many('campaign.partner.history', 'camp_partner_id', 'History'),
        'campaign_id': fields.many2one('campaign.campaign', 'Campaign'),
        'state': fields.selection([('draft','Normal'), ('wait','Waiting'), ('stop','Stopped')], 'State', readonly=True)
    }
    _defaults = {
        'state': lambda *a: 'draft',
        'active': lambda *a: 1
    }
    _order = 'state,priority desc,name'

    def recall(self,cr, uid, ids, *args):
        res = self.read(cr,uid,ids,['date_recall', 'name', 'info', 'step'])
        for r in res:
            if not r['date_recall']:
                raise orm.except_orm('ValidateError', ('Error, choose a date', 'date_recall'))

        for r in res:
            self.pool.get('campaign.partner.history').create(cr, uid, {
                'name': 'Recall Later ' + str(r['date_recall']),
                'info': r['info'],
                'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                'step_id': r['step'][0],
                'camp_partner_id': r['id']
            })
            self.pool.get('ir.cron').create(cr, uid, {
                'user_id': uid,
                'name': 'Campaign: Recall',
                'nextcall': r['date_recall'],
                'active': True,
                'numbercall': 1,
                'model': self._name,
                'function': 'write',
                'args': repr([[r['id']], {'date_recall':False, 'state':'draft'}])
            })
        self.write(cr, uid, ids, {'state':'wait'})
        return True

    def stop_camp(self,cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state':'stop', 'active':0})
        return True

    def continue_camp(self, cr, uid, ids, *args):
        res = self.read(cr, uid, ids, ['info', 'state', 'step', 'campaign_id'])
        for r in res:
            self.pool.get('campaign.partner.history').create(cr, uid, {
                'name': r['step'][1],
                'info': r['info'],
                'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                'step_id': r['step'][0],
                'camp_partner_id': r['id']
            })
            cr.execute('select id,start_date from campaign_step where priority>(select priority from campaign_step where id=%d) and campaign_id=%d order by priority limit 1', (r['step'][0],r['campaign_id'][0]))
            nextstep = cr.fetchone()
            if nextstep:
                dt = False
                if nextstep[1] > time.strftime('%Y-%m-%d'):
                    dt = nextstep[1]
                self.write(cr, uid, [r['id']], {
                    'step': nextstep[0],
                    'state': 'draft',
                    'info': '',
                    'date_recall': dt,
                    'active': True
                })
                if dt:
                    self.recall(cr, uid, [r['id']])
        return True
class account_financial_report(osv.osv):
    _name = "afr"

    _columns = {
        'name':
        fields.char('Name', size=128, required=True),
        'company_id':
        fields.many2one('res.company', 'Company', required=True),
        'currency_id':
        fields.many2one(
            'res.currency',
            'Currency',
            help=
            "Currency at which this report will be expressed. If not selected will be used the one set in the company"
        ),
        'inf_type':
        fields.selection([('BS', 'Balance Sheet'), ('IS', 'Income Statement')],
                         'Type',
                         required=True),
        'columns':
        fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'),
                          ('four', 'Initial | Debit | Credit | YTD'),
                          ('five', 'Initial | Debit | Credit | Period | YTD'),
                          ('qtr', "4 QTR's | YTD"),
                          ('thirteen', '12 Months | YTD')],
                         'Columns',
                         required=True),
        'display_account':
        fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'),
                          ('mov', 'With movements'),
                          ('bal_mov', 'With Balance / Movements')],
                         'Display accounts'),
        'display_account_level':
        fields.integer(
            'Up to level',
            help='Display accounts up to this level (0 to show all)'),
        'account_ids':
        fields.many2many('account.account',
                         'afr_account_rel',
                         'afr_id',
                         'account_id',
                         'Root accounts',
                         required=True),
        'fiscalyear_id':
        fields.many2one('account.fiscalyear',
                        'Fiscal year',
                        help='Fiscal Year for this report',
                        required=True),
        'period_ids':
        fields.many2many('account.period',
                         'afr_period_rel',
                         'afr_id',
                         'period_id',
                         'Periods',
                         help='All periods in the fiscal year if empty'),
        'analytic_ledger':
        fields.boolean(
            'Analytic Ledger',
            help=
            "Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"
        ),
        'journal_ledger':
        fields.boolean(
            'journal Ledger',
            help=
            "Allows to Generate an journal Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"
        ),
        'partner_balance':
        fields.boolean(
            'Partner Balance',
            help="Allows to "
            "Generate a Partner Balance for accounts with moves. Available when "
            "Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
        'tot_check':
        fields.boolean(
            'Summarize?',
            help=
            'Checking will add a new line at the end of the Report which will Summarize Columns in Report'
        ),
        'lab_str':
        fields.char('Description',
                    help='Description for the Summary',
                    size=128),
        'target_move':
        fields.selection(
            [
                ('posted', 'All Posted Entries'),
                ('all', 'All Entries'),
            ],
            'Entries to Include',
            required=True,
            help=
            'Print All Accounting Entries or just Posted Accounting Entries'),

        #~ Deprecated fields
        'filter':
        fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'),
                          ('all', 'By Date and Period'),
                          ('none', 'No Filter')], 'Date/Period Filter'),
        'date_to':
        fields.date('End date'),
        'date_from':
        fields.date('Start date'),
    }

    _defaults = {
        'display_account_level':
        lambda *a: 0,
        'inf_type':
        lambda *a: 'BS',
        'company_id':
        lambda self, cr, uid, c: self.pool.get('res.company').
        _company_default_get(cr, uid, 'account.invoice', context=c),
        'fiscalyear_id':
        lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(
            cr, uid),
        'display_account':
        lambda *a: 'bal_mov',
        'columns':
        lambda *a: 'five',
        'date_from':
        lambda *a: time.strftime('%Y-%m-%d'),
        'date_to':
        lambda *a: time.strftime('%Y-%m-%d'),
        'filter':
        lambda *a: 'byperiod',
        'target_move':
        'posted',
    }

    def copy(self, cr, uid, id, defaults, context=None):
        if context is None:
            context = {}
        previous_name = self.browse(cr, uid, id, context=context).name
        new_name = _('Copy of %s') % previous_name
        lst = self.search(cr,
                          uid, [('name', 'like', new_name)],
                          context=context)
        if lst:
            new_name = '%s (%s)' % (new_name, len(lst) + 1)
        defaults['name'] = new_name
        return (super(account_financial_report, self).copy(cr,
                                                           uid,
                                                           id,
                                                           defaults,
                                                           context=context))

    def onchange_inf_type(self, cr, uid, ids, inf_type, context=None):
        if context is None:
            context = {}
        res = {'value': {}}

        if inf_type != 'BS':
            res['value'].update({'analytic_ledger': False})

        return res

    def onchange_columns(self,
                         cr,
                         uid,
                         ids,
                         columns,
                         fiscalyear_id,
                         period_ids,
                         context=None):
        if context is None:
            context = {}
        res = {'value': {}}

        if columns != 'four':
            res['value'].update({'analytic_ledger': False})

        if columns in ('qtr', 'thirteen'):
            p_obj = self.pool.get("account.period")
            period_ids = p_obj.search(cr,
                                      uid,
                                      [('fiscalyear_id', '=', fiscalyear_id),
                                       ('special', '=', False)],
                                      context=context)
            res['value'].update({'period_ids': period_ids})
        else:
            res['value'].update({'period_ids': []})
        return res

    def onchange_analytic_ledger(self,
                                 cr,
                                 uid,
                                 ids,
                                 company_id,
                                 analytic_ledger,
                                 context=None):
        if context is None:
            context = {}
        context['company_id'] = company_id
        res = {'value': {}}
        cur_id = self.pool.get('res.company').browse(
            cr, uid, company_id, context=context).currency_id.id
        res['value'].update({'currency_id': cur_id})
        return res

    def onchange_company_id(self, cr, uid, ids, company_id, context=None):
        if context is None:
            context = {}
        context['company_id'] = company_id
        res = {'value': {}}

        if not company_id:
            return res

        cur_id = self.pool.get('res.company').browse(
            cr, uid, company_id, context=context).currency_id.id
        fy_id = self.pool.get('account.fiscalyear').find(cr,
                                                         uid,
                                                         context=context)
        res['value'].update({'fiscalyear_id': fy_id})
        res['value'].update({'currency_id': cur_id})
        res['value'].update({'account_ids': []})
        res['value'].update({'period_ids': []})
        return res
Пример #17
0
     "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",
         required=True,
     ),
     "state": fields.selection([("na", "Not Applicable"), ("sending", "Sending")], "Status", required=True),
     "date_mail": fields.datetime("Rec/Sent Date", help="Date on which Email Sent or Received"),
     "history": fields.text("History", readonly=True, store=True),
 }
Пример #18
0
class res_partner(osv.osv):
    _description = 'Partner'
    _name = "res.partner"
    _order = "name"

    def _get_default_partner_address_details(self,
                                             cr,
                                             uid,
                                             ids,
                                             name,
                                             args,
                                             context=None):
        result = {}
        for address_id in ids:
            res = {}
            cr.execute(
                """SELECT city, function, name, phone, mobile, country_id, email
                        FROM res_partner_address
                        WHERE partner_id = %s
                        AND type = 'default'
                        AND active = True
                        LIMIT 1""", (address_id, ))
            default_address = cr.fetchone()
            if default_address:
                res['city'] = default_address[0]
                res['function'] = default_address[1]
                res['subname'] = default_address[2]
                res['phone'] = default_address[3]
                res['mobile'] = default_address[4]
                res['country'] = default_address[5]
                res['email'] = default_address[6]
            else:
                cr.execute(
                    """SELECT city, function, name, phone, mobile, country_id, email
                        FROM res_partner_address
                        WHERE partner_id = %s
                        AND active = True
                        LIMIT 1""", (address_id, ))
                first_address = cr.fetchone()
                if first_address:
                    res['city'] = first_address[0]
                    res['function'] = first_address[1]
                    res['subname'] = first_address[2]
                    res['phone'] = first_address[3]
                    res['mobile'] = first_address[4]
                    res['country'] = first_address[5]
                    res['email'] = first_address[6]
            result[address_id] = res
        return result

    _columns = {
        'name':
        fields.char('Name', size=128, required=True, select=True),
        'date':
        fields.date('Date', select=1),
        'title':
        fields.many2one('res.partner.title', 'Partner Firm'),
        'parent_id':
        fields.many2one('res.partner', 'Parent Partner'),
        'child_ids':
        fields.one2many('res.partner', 'parent_id', 'Partner Ref.'),
        'ref':
        fields.char('Reference', size=64, select=1),
        'lang':
        fields.selection(
            _lang_get,
            'Language',
            help=
            "If the selected language is loaded in the system, all documents related to this partner will be printed in this language. If not, it will be english."
        ),
        'user_id':
        fields.many2one(
            'res.users',
            'Salesman',
            help=
            'The internal user that is in charge of communicating with this partner if any.'
        ),
        'vat':
        fields.char(
            'VAT',
            size=32,
            help=
            "Value Added Tax number. Check the box if the partner is subjected to the VAT. Used by the VAT legal statement."
        ),
        'bank_ids':
        fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
        'website':
        fields.char('Website', size=64, help="Website of Partner."),
        'comment':
        fields.text('Notes'),
        'address':
        fields.one2many('res.partner.address', 'partner_id', 'Contacts'),
        'category_id':
        fields.many2many('res.partner.category', 'res_partner_category_rel',
                         'partner_id', 'category_id', 'Categories'),
        'events':
        fields.one2many('res.partner.event', 'partner_id', 'Events'),
        'credit_limit':
        fields.float(string='Credit Limit'),
        'ean13':
        fields.char('EAN13', size=13),
        'active':
        fields.boolean('Active'),
        'customer':
        fields.boolean('Customer',
                       help="Check this box if the partner is a customer."),
        'supplier':
        fields.boolean(
            'Supplier',
            help=
            "Check this box if the partner is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."
        ),
        'city':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="City",
                        type="char"),
        #'city': fields.related('address', 'city', type='char', string='City'),
        'function':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="function",
                        type="char"),
        #'function': fields.related('address', 'function', type='char', string='function'),
        'subname':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="Contact Name",
                        type="char"),
        #'subname': fields.related('address', 'name', type='char', string='Contact Name'),
        'phone':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="Phone",
                        type="char"),
        #'phone': fields.related('address', 'phone', type='char', string='Phone'),
        'mobile':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="Mobile",
                        type="char"),
        #'mobile': fields.related('address', 'mobile', type='char', string='Mobile'),
        'country':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="Country",
                        type='many2one',
                        relation='res.country'),
        #'country': fields.related('address', 'country_id', type='many2one', relation='res.country', string='Country'),
        'employee':
        fields.boolean('Employee',
                       help="Check this box if the partner is an Employee."),
        'email':
        fields.function(_get_default_partner_address_details,
                        method=True,
                        multi='defaultaddress',
                        store=False,
                        string="E-mail",
                        type="char"),
        #'email': fields.related('address', 'email', type='char', size=240, string='E-mail'),
        'company_id':
        fields.many2one('res.company', 'Company', select=1),
        'color':
        fields.integer('Color Index'),
    }

    def _default_category(self, cr, uid, context=None):
        if context is None:
            context = {}
        if 'category_id' in context and context['category_id']:
            return [context['category_id']]
        return []

    _defaults = {
        'active':
        lambda *a: 1,
        'customer':
        lambda *a: 1,
        'category_id':
        _default_category,
        'company_id':
        lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(
            cr, uid, 'res.partner', context=c),
        'color':
        0,
    }

    def copy(self, cr, uid, id, default=None, context=None):
        if default is None:
            default = {}
        name = self.read(cr, uid, [id], ['name'], context)[0]['name']
        default.update({'name': name + _(' (copy)'), 'events': []})
        return super(res_partner, self).copy(cr, uid, id, default, context)

    def do_share(self, cr, uid, ids, *args):
        return True

    def _check_ean_key(self, cr, uid, ids, context=None):
        for partner_o in pooler.get_pool(cr.dbname).get('res.partner').read(
                cr, uid, ids, [
                    'ean13',
                ]):
            thisean = partner_o['ean13']
            if thisean and thisean != '':
                if len(thisean) != 13:
                    return False
                sum = 0
                for i in range(12):
                    if not (i % 2):
                        sum += int(thisean[i])
                    else:
                        sum += 3 * int(thisean[i])
                if math.ceil(sum / 10.0) * 10 - sum != int(thisean[12]):
                    return False
        return True


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

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if not len(ids):
            return []
        if context.get('show_ref'):
            rec_name = 'ref'
        else:
            rec_name = 'name'

        res = [(r['id'], r[rec_name])
               for r in self.read(cr, uid, ids, [rec_name], context)]
        return res

    def name_search(self,
                    cr,
                    uid,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        # short-circuit ref match when possible
        if name and operator in ('=', 'ilike', '=ilike', 'like'):
            ids = self.search(cr,
                              uid, [('ref', '=', name)] + args,
                              limit=limit,
                              context=context)
            if ids:
                return self.name_get(cr, uid, ids, context)
        return super(res_partner, self).name_search(cr,
                                                    uid,
                                                    name,
                                                    args,
                                                    operator=operator,
                                                    context=context,
                                                    limit=limit)

    def _email_send(self,
                    cr,
                    uid,
                    ids,
                    email_from,
                    subject,
                    body,
                    on_error=None):
        partners = self.browse(cr, uid, ids)
        for partner in partners:
            if len(partner.address):
                if partner.address[0].email:
                    tools.email_send(email_from, [partner.address[0].email],
                                     subject, body, on_error)
        return True

    def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
        while len(ids):
            self.pool.get('ir.cron').create(
                cr,
                uid,
                {
                    'name': 'Send Partner Emails',
                    'user_id': uid,
                    #               'nextcall': False,
                    'model': 'res.partner',
                    'function': '_email_send',
                    'args': repr(
                        [ids[:16], email_from, subject, body, on_error])
                })
            ids = ids[16:]
        return True

    def address_get(self, cr, uid, ids, adr_pref=None):
        if adr_pref is None:
            adr_pref = ['default']
        address_obj = self.pool.get('res.partner.address')
        address_ids = address_obj.search(cr, uid, [('partner_id', 'in', ids)])
        address_rec = address_obj.read(cr, uid, address_ids, ['type'])
        res = list((addr['type'], addr['id']) for addr in address_rec)
        adr = dict(res)
        # get the id of the (first) default address if there is one,
        # otherwise get the id of the first address in the list
        if res:
            default_address = adr.get('default', res[0][1])
        else:
            default_address = False
        result = {}
        for a in adr_pref:
            result[a] = adr.get(a, default_address)
        return result

    def gen_next_ref(self, cr, uid, ids):
        if len(ids) != 1:
            return True

        # compute the next number ref
        cr.execute(
            "select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1"
        )
        res = cr.dictfetchall()
        ref = res and res[0]['ref'] or '0'
        try:
            nextref = int(ref) + 1
        except:
            raise osv.except_osv(
                _('Warning'),
                _("Couldn't generate the next id because some partners have an alphabetic id !"
                  ))

        # update the current partner
        cr.execute("update res_partner set ref=%s where id=%s",
                   (nextref, ids[0]))
        return True

    def view_header_get(self, cr, uid, view_id, view_type, context):
        res = super(res_partner, self).view_header_get(cr, uid, view_id,
                                                       view_type, context)
        if res: return res
        if (not context.get('category_id')
                or not isinstance(context['category_id'], (int, long))):
            return False
        return _('Partners: ') + self.pool.get('res.partner.category').browse(
            cr, uid, context['category_id'], context).name

    def main_partner(self, cr, uid):
        ''' Return the id of the main partner
        '''
        model_data = self.pool.get('ir.model.data')
        return model_data.browse(
            cr,
            uid,
            model_data.search(cr, uid, [('module', '=', 'base'),
                                        ('name', '=', 'main_partner')])[0],
        ).res_id
Пример #19
0
        ###################################
        warning = self.make_warning_message()
        res_text = '\n'
        for i in sorted(self.imported_records):
            res_text+=i+': '+str(len(self.imported_records[i]))+'\n'
        self.imported_records.clear()
        self.warning_text = []
        self.write(cr, uid, self_id, {'log':warning+res_text,'state':'done'})
        return

    _columns = {
        'name':fields.char('Name', size=64),
        'date': fields.date('Date', required=True),
        'import_model_ids':fields.many2many('migration.import_models', 'schedule_models_rel', 'schedule_id', 'import_model_id', 'Import Models'),
        'actions_ids': fields.many2many('migration.model_actions', 'schedule_actions_rel', 'schedule_id', 'action_id', 'Actions'),
        'state':fields.selection([('ready','Ready'),('running','Running'),('error','Error'),('done','Done'),('stop','Stopped')], 'State'),
        'log': fields.text('Log'),
        'print_log':fields.boolean('Print Log to Console'),
        'cron_id':fields.many2one('ir.cron', 'Scheduler', readonly=True),
                
    }
    _defaults = {
        'date': lambda *a: time.strftime('%Y-%m-%d'),
        'state': lambda *a: 'ready',
    }

    def set_start(self, cr, uid, ids, context={}):
        self.write(cr, uid, ids, {'state':'ready'})
        cron_id = self.browse(cr, uid, ids[0], {}).cron_id.id
        nextcall = (now()+DateTime.RelativeDateTime(seconds=30)).strftime('%Y-%m-%d %H:%M:%S')
        self.pool.get('ir.cron').write(cr, uid, cron_id, {'numbercall':1, 'active':True, 'nextcall':nextcall})
Пример #20
0
class res_partner_address(osv.osv):
    _description = 'Partner Addresses'
    _name = 'res.partner.address'
    _order = 'type, name'
    _columns = {
        'partner_id':
        fields.many2one(
            'res.partner',
            'Partner Name',
            ondelete='set null',
            select=True,
            help="Keep empty for a private address, not related to partner."),
        'type':
        fields.selection(
            [('default', 'Default'), ('invoice', 'Invoice'),
             ('delivery', 'Delivery'), ('contact', 'Contact'),
             ('other', 'Other')],
            'Address Type',
            help=
            "Used to select automatically the right address according to the context in sales and purchases documents."
        ),
        'function':
        fields.char('Function', size=128),
        'title':
        fields.many2one('res.partner.title', 'Title'),
        'name':
        fields.char('Contact Name', size=64, select=1),
        'street':
        fields.char('Street', size=128),
        'street2':
        fields.char('Street2', size=128),
        'zip':
        fields.char('Zip', change_default=True, size=24),
        'city':
        fields.char('City', size=128),
        'state_id':
        fields.many2one("res.country.state",
                        'Fed. State',
                        domain="[('country_id','=',country_id)]"),
        'country_id':
        fields.many2one('res.country', 'Country'),
        'email':
        fields.char('E-Mail', size=240),
        'phone':
        fields.char('Phone', size=64),
        'fax':
        fields.char('Fax', size=64),
        'mobile':
        fields.char('Mobile', size=64),
        'birthdate':
        fields.char('Birthdate', size=64),
        'is_customer_add':
        fields.related('partner_id',
                       'customer',
                       type='boolean',
                       string='Customer'),
        'is_supplier_add':
        fields.related('partner_id',
                       'supplier',
                       type='boolean',
                       string='Supplier'),
        'active':
        fields.boolean('Active',
                       help="Uncheck the active field to hide the contact."),
        #        'company_id': fields.related('partner_id','company_id',type='many2one',relation='res.company',string='Company', store=True),
        'company_id':
        fields.many2one('res.company', 'Company', select=1),
        'color':
        fields.integer('Color Index'),
        'ref':
        fields.char(
            'Ref',
            size=256,
        ),
    }
    _defaults = {
        'active':
        lambda *a: 1,
        'company_id':
        lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(
            cr, uid, 'res.partner.address', context=c),
    }

    def name_get(self, cr, user, ids, context=None):
        if context is None:
            context = {}
        fields_to_read = context.get('fields_to_read') or [
            'name', 'zip', 'country_id', 'city', 'partner_id', 'street', 'ref',
            'state_id'
        ]
        if not len(ids):
            return []
        res = []
        for r in self.read(cr, user, ids, fields_to_read):
            if context.get('contact_display',
                           'contact') == 'partner' and r['partner_id']:
                res.append((r['id'], r['partner_id'][1]))
            else:
                # make a comma-separated list with the following non-empty elements
                elems = []
                for field_name in fields_to_read:
                    #get field name for many2one and char,etc.. fields
                    if (r[field_name] and type(r[field_name]) in (list, tuple)
                            and len(r[field_name]) > 1):
                        elems.append(r[field_name][1])
                    else:
                        elems.append(r[field_name])
                addr = ', '.join(filter(bool, elems))
                if (context.get('contact_display', 'contact')
                        == 'partner_address') and r['partner_id']:
                    res.append((r['id'],
                                "%s: %s" % (r['partner_id'][1], addr or '/')))
                else:
                    res.append((r['id'], addr or '/'))
        return res

    def name_search(self,
                    cr,
                    user,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        if context is None:
            context = {}

        if not name:
            ids = self.search(cr, user, args, limit=limit, context=context)
        elif context.get('contact_display', 'contact') == 'partner':
            ids = self.search(cr,
                              user, [('partner_id', operator, name)] + args,
                              limit=limit,
                              context=context)
        else:
            # first lookup zip code, as it is a common and efficient way to search on these data
            ids = self.search(cr,
                              user, [('zip', '=', name)] + args,
                              limit=limit,
                              context=context)
            # then search on other fields:
            if context.get('contact_display', 'contact') == 'partner_address':
                fields = [
                    'partner_id', 'ref', 'name', 'street', 'zip', 'state_id'
                ]
            else:
                fields = ['ref', 'name', 'street', 'zip', 'state_id']
            # Here we have to search the records that satisfy the domain:
            #       OR([[(f, operator, name)] for f in fields])) + args
            # Searching on such a domain can be dramatically inefficient, due to the expansion made
            # for field translations, and the handling of the disjunction by the DB engine itself.
            # So instead, we search field by field until the search limit is reached.
            while (not limit or len(ids) < limit) and fields:
                f = fields.pop(0)
                new_ids = self.search(cr,
                                      user, [(f, operator, name)] + args,
                                      limit=(limit -
                                             len(ids) if limit else limit),
                                      context=context)
                # extend ids with the ones in new_ids that are not in ids yet (and keep order)
                old_ids = set(ids)
                ids.extend([id for id in new_ids if id not in old_ids])

        if limit:
            ids = ids[:limit]
        return self.name_get(cr, user, ids, context=context)

    def get_city(self, cr, uid, id):
        return self.browse(cr, uid, id).city

    def _display_address(self, cr, uid, address, context=None):
        '''
        The purpose of this function is to build and return an address formatted accordingly to the
        standards of the country where it belongs.

        :param address: browse record of the res.partner.address to format
        :returns: the address formatted in a display that fit its country habits (or the default ones
            if not country is specified)
        :rtype: string
        '''
        # get the address format
        address_format = address.country_id and address.country_id.address_format or \
                                         '%(street)s\n%(street2)s\n%(city)s,%(state_code)s %(zip)s'
        # get the information that will be injected into the display format
        args = {
            'state_code': address.state_id and address.state_id.code or '',
            'state_name': address.state_id and address.state_id.name or '',
            'country_code': address.country_id and address.country_id.code
            or '',
            'country_name': address.country_id and address.country_id.name
            or '',
        }
        address_field = ['title', 'street', 'street2', 'zip', 'city']
        for field in address_field:
            args[field] = getattr(address, field) or ''

        return address_format % args
Пример #21
0
        return True

    def _valid_get(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        for contract in self.browse(cr, uid, ids, context=context):
            res[contract.id] = ("unvalid", "valid")[contract.date_stop >= time.strftime('%Y-%m-%d')]
        return res

    _columns = {
        'name' : fields.char('Contract ID', size=256, required=True, readonly=True),
        'password' : fields.char('Password', size=64, invisible=True, required=True, readonly=True),
        'date_start' : fields.date('Starting Date', readonly=True),
        'date_stop' : fields.date('Ending Date', readonly=True),
        'module_ids' : fields.many2many('maintenance.contract.module', 'maintenance_contract_module_rel', 'contract_id', 'module_id', 'Covered Modules', readonly=True),
        'state' : fields.function(_valid_get, method=True, string="State", type="selection", selection=[('valid', 'Valid'),('unvalid', 'Unvalid')], readonly=True),
        'kind' : fields.selection([('full', 'Full'),('partial', 'Partial')], 'Kind', required=True, readonly=True),
    }
    _defaults = {
        'password' : lambda obj,cr,uid,context={} : '',
    }
    _sql_constraints = [
        ('uniq_name', 'unique(name)', "Your maintenance contract is already subscribed in the system !")
    ]

maintenance_contract()


class maintenance_contract_wizard(osv.osv_memory):
    _name = 'maintenance.contract.wizard'

    _columns = {
class dep_issue_register_wizard(osv.osv_memory):
	
	_name = "dep.issue.register.wizard"
	_description = "Issue Register Wiz"
	
	_columns = {
				
				'fis_year'	  : fields.many2one('account.fiscalyear','Fiscal year',readonly=True),
				'user_id'	  : fields.many2one('res.users', 'User ID'),
				'company_id'  : fields.many2one('res.company', 'Company Name',required=True),
				'from_date'   : fields.date('From Date'),
				'to_date'	  : fields.date('To Date'),
				'dep_id'	  : fields.many2many('kg.depmaster','dep_issue_register2','wiz_id','dep_id','Department',domain="[('state','in',('draft','confirm','approved'))]"),
				'product' 	  : fields.many2many('product.product','dep_issue_product2','product_wiz_id','product_dep_id','Product',domain="[('state','in',('draft','confirm','approved'))]"),
				'moc_id' 	  : fields.many2many('kg.moc.master','dep_issue_wiz','wiz_id','moc_id','MOC'),
				'issue_status': fields.selection([('approved', 'Approved'),('cancelled','Cancelled')], "Status"),
				'filter'	  : fields.selection([('filter_no', 'No Filters'), ('filter_date', 'Date')], "Filter by"),
				'print_date'  : fields.datetime('Creation Date', readonly=True),
				
			}
	
	def _get_from_date(self, cr, uid, context=None):
		today = date.today()
		fis_obj = self.pool.get('account.fiscalyear').search(cr, uid, [('date_start','<=',today),('date_stop','>=',today)])
		fis_id = self.pool.get('account.fiscalyear').browse(cr,uid,fis_obj[0])
		from_date = fis_id.date_start
		d2 = datetime.strptime(from_date,'%Y-%m-%d')
		res = d2.strftime('%Y-%m-%d')
		return res
	
	def _get_fis(self, cr, uid, context=None):
		today = date.today()
		fis_obj = self.pool.get('account.fiscalyear').search(cr, uid, [('date_start','<=',today),('date_stop','>=',today)])
		fis_id = self.pool.get('account.fiscalyear').browse(cr,uid,fis_obj[0])
		fisyear_id = fis_id.id
		return fisyear_id
	
	_defaults = {
				
				'user_id'	: lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).id,
				'company_id': 1,
				'from_date' : lambda * a: time.strftime('%Y-%m-%d'),
				'to_date'	: lambda * a: time.strftime('%Y-%m-%d'),
				'fis_year'	: _get_fis,
				'filter'	: 'filter_date',
				'print_date': lambda * a: time.strftime('%Y-%m-%d %H:%M:%S'),
				
				}
	
	def create_report(self, cr, uid, ids, context={}):
		data = self.read(cr,uid,ids,)[-1]
		#~ print data,' create_report('
		return {
			'type'		  : 'ir.actions.report.xml',
			'report_name' : 'jasper_kg_dep_issue',
			'datas'		  : {
							'model'		 : 'dep.issue.register.wizard',
							'id'		 : context.get('active_ids') and context.get('active_ids')[0] or False,
							'ids'		 : context.get('active_ids') and context.get('active_ids') or [],
							'report_type': 'pdf',
							'form'		 : data
							},
			'nodestroy': False
			}
	
	def _enddate_check(self,cr,uid,ids,context=None):
		rec=self.browse(cr,uid,ids[0])
		if rec.to_date < rec.from_date:
			raise osv.except_osv(_('Warning!'),_('End Date is lesser than Start Date!!'))
		return True
	
	_constraints = [
		
		(_enddate_check, 'Future Dates are Not Allowed !!!', ['Check Date']),
		
	]
Пример #23
0
        res = obj.read(cr, uid, ids, ['code', 'name'], context)
        return [(r['code'], r['name']) for r in res]

    def _get_xml_id(self, cr, uid, ids, *args, **kwargs):
        model_data_obj = self.pool.get('ir.model.data')
        data_ids = model_data_obj.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
        data_results = model_data_obj.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
        result = {}
        for id in ids:
            result[id] = False
        for record in data_results:
            result[record['res_id']] = '%(module)s.%(name)s' % record
        return result

    _columns = {
        'charset':fields.selection(_get_encodings, string='Charset', required=True),
        'content_fname': fields.char('Override Extension',size=64, help='Here you can override output file extension'),
        'styles_mode': fields.selection([
            ('default','Not used'),
            ('global', 'Global'),
            ('specified', 'Specified'),
            ], string='Stylesheet'),
        #'report_styles' : fields.binary('Template Styles', help='OpenOffice stylesheet (.odt)'),
        'stylesheet_id':fields.many2one('report.stylesheets', 'Template Stylesheet'),
        'preload_mode':fields.selection([
            ('static',_('Static')),
            ('preload',_('Preload')),
        ],'Preload Mode'),
        'tml_source':fields.selection([
            ('database','Database'),
            ('file','File'),
Пример #24
0
class oehealth_medicament(osv.Model):
    _name = 'oehealth.medicament'
    _description = "Medicament"
    _inherits = {
        'product.product': 'product_id',
    }

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

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

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

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

    def name_get(self, cr, uid, ids, context={}):
        if not len(ids):
            return []
        reads = self.read(cr,
                          uid,
                          ids, ['name_active_component'],
                          context=context)
        res = []
        for record in reads:
            name = record['name_active_component']
            res.append((record['id'], name))
        return res

    def name_active_component_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if isinstance(ids, (int, long)):
            ids = [ids]
        reads = self.read(cr,
                          uid,
                          ids, ['name', 'active_component_name'],
                          context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['active_component_name']:
                #name = name + ' (' + record['active_component'][1] + ')'
                name = name + ' (' + record['active_component_name'] + ')'
            res.append((record['id'], name))
        return res

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

    _columns = {
        'product_id': fields.many2one('product.product', 'Product', required=True,
                                      ondelete='cascade', help='Product-related data of the medicament'),
        #we need a related field in order to be able to sort the medicament by name
        'name_product': fields.related('product_id', 'name', type='char', string='Related Product',
                                       readonly=True, store=True),
        'medicament_category': fields.many2one('oehealth.medicament.category',
                                               'Medicament Category',select=True),
        'medicament_code': fields.char(size=64, string='Code', required=False),
        'medicament_name': fields.char(size=256, string='Name'),
        'active_component': fields.many2one('oehealth.medicament.active_component', string='Active Component',
                                             help='Medicament Active Component'),
        'active_component_name': fields.related('active_component', 'name', type='char', string='Related Active Component',
                                                readonly=True, store=True),
        'concentration': fields.char(size=256, string='Concentration'),
        'presentation': fields.char(size=256, string='Presentation'),
        'pres2': fields.integer(string='Pres2', help='Presentation Quantity'),
        'pres3': fields.char(size=256, string='Presentation Form'),
        'composition': fields.text(string='Composition', help='Components'),
        'name_active_component': fields.function(_name_active_component_get_fnc, type="char", string='Name (Active Component)'),
        'indications': fields.text(string='Indication', help='Indications'),
        'therapeutic_action': fields.char(size=256,
                                          string='Therapeutic effect',
                                          help='Therapeutic action'),
        'pregnancy_category': fields.selection([('A', 'A'),
                                                ('B', 'B'),
                                                ('C', 'C'),
                                                ('D', 'D'),
                                                ('X', 'X'),
                                                ('N', 'N'),
                                                ], string='Pregnancy Category',
                                               help='** FDA Pregancy Categories ***\n'\
                                                    'CATEGORY A :Adequate and well-controlled human studies have failed'\
                                                    ' to demonstrate a risk to the fetus in the first trimester of'\
                                                    ' pregnancy (and there is no evidence of risk in later'\
                                                    ' trimesters).\n\n'\
                                                    'CATEGORY B : Animal reproduction studies have failed todemonstrate a'\
                                                    ' risk to the fetus and there are no adequate and well-controlled'\
                                                    ' studies in pregnant women OR Animal studies have shown an adverse'\
                                                    ' effect, but adequate and well-controlled studies in pregnant women'\
                                                    ' have failed to demonstrate a risk to the fetus in any'\
                                                    ' trimester.\n\n'
                                                    'CATEGORY C : Animal reproduction studies have shown an adverse'\
                                                    ' effect on the fetus and there are no adequate and well-controlled'\
                                                    ' studies in humans, but potential benefits may warrant use of the'\
                                                    ' drug in pregnant women despite potential risks. \n\n '\
                                                    'CATEGORY D : There is positive evidence of human fetal  risk based'\
                                                    ' on adverse reaction data from investigational or marketing'\
                                                    ' experience or studies in humans, but potential benefits may warrant'\
                                                    ' use of the drug in pregnant women despite potential risks.\n\n'\
                                                    'CATEGORY X : Studies in animals or humans have demonstrated fetal'\
                                                    ' abnormalities and/or there is positive evidence of human fetal risk'\
                                                    ' based on adverse reaction data from investigational or marketing'\
                                                    ' experience, and the risks involved in use of the drug in pregnant'\
                                                    ' women clearly outweigh potential benefits.\n\n'\
                                                    'CATEGORY N : Not yet classified'),
        'overdosage': fields.text(string='Overdosage', help='Overdosage'),
        'pregnancy_warning': fields.boolean(string='Pregnancy Warning',
                                            help='The drug represents risk to pregnancy or lactancy'),
        'medicament_notes': fields.text(string='Medicament Info'),
        'storage': fields.text(string='Storage Conditions'),
        'adverse_reaction': fields.text(string='Adverse Reactions'),
        'dosage': fields.text(string='Dosage Instructions',
                              help='Dosage / Indications'),
        'pregnancy': fields.text(string='Pregnancy and Lactancy',
                                 help='Warnings for Pregnant Women'),
        'date_medicament_inclusion' : fields.date('Medicament Inclusion Date'),
        'date_medicament_activation' : fields.date('Medicament Activation Date'),
        'date_medicament_inactivation' : fields.date('Medicament Inactivation Date'),
        'date_medicament_suspension' : fields.date('Medicament Suspension Date'),
        'medicament_annotation_ids': fields.one2many('oehealth.annotation',
                                                     'medicament_id',
                                                     'Medicament Annotations'),
        'medicament_rgss': fields.selection([('U', 'Undefined'),
                                             ('R', 'Reference'),
                                             ('G', 'Generic'),
                                             ('S', 'Similar'),
                                             ], string='Medicament Status',
                                                  select=True, sort=False, required=False, translate=True),
        'medicament_tag_ids': fields.many2many('oehealth.tag',
                                               'oehealth_medicament_tag_rel',
                                               'medicament_id',
                                               'tag_id',
                                               'Tags'),
        'medicament_status': fields.selection([('U', 'Undefined'),
                                               ('A', 'Activated'),
                                               ('I', 'Inactivated'),
                                               ('S', 'Suspended'),
                                               ], string='Medicament Status',
                                                  select=True, sort=False, required=False, translate=True),
        'state': fields.selection([('new','New'),
                                   ('revised','Revised'),
                                   ('waiting','Waiting'),
                                   ('okay','Okay')], 'Stage', readonly=True),
        'therapeutic_class': fields.many2one('oehealth.medicament.therapeutic_class', string='Therapeutic Class',
                                             help='Medicament Therapeutic Class'),
        'manufacturer': fields.many2one('oehealth.medicament.manufacturer', string='Manufacturer',
                                        help='Medicament Manufacturer'),
        'create_uid': fields.function(_compute_create_uid, method=True, type='char', string='Create User',),
        'create_date': fields.function(_compute_create_date, method=True, type='datetime', string='Create Date',),
        'write_uid': fields.function(_compute_write_uid, method=True, type='char', string='Write User',),
        'write_date': fields.function(_compute_write_date, method=True, type='datetime', string='Write Date',),
    }

    _order = 'name_product'

    _sql_constraints = [('medicament_code_uniq', 'unique(medicament_code)',
                         u'Duplicated Medicament Code!')]

    _defaults = {
        'medicament_code': '/',
        'active': 1,
        'is_medicament': True,
        'medicament_status': 'U',
        'state': 'new',
    }

    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}
        if not 'medicament_code' in vals or vals['medicament_code'] == '/':
            val = self.pool.get('ir.sequence').get(cr, uid,
                                                   'oehealth.medicament.code')
            code = map(int, str(val))
            code_len = len(code)
            while len(code) < 14:
                code.insert(0, 0)
            while len(code) < 16:
                n = sum([(len(code) + 1 - i) * v
                         for i, v in enumerate(code)]) % 11
                if n > 1:
                    f = 11 - n
                else:
                    f = 0
                code.append(f)
            code_str = "%s.%s.%s.%s.%s-%s" % (
                str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) +
                str(code[4]), str(code[5]) + str(code[6]) + str(code[7]),
                str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) +
                str(code[12]) + str(code[13]), str(code[14]) + str(code[15]))
            if code_len <= 3:
                vals['medicament_code'] = code_str[18 - code_len:21]
            elif code_len > 3 and code_len <= 6:
                vals['medicament_code'] = code_str[17 - code_len:21]
            elif code_len > 6 and code_len <= 9:
                vals['medicament_code'] = code_str[16 - code_len:21]
            elif code_len > 9 and code_len <= 12:
                vals['medicament_code'] = code_str[15 - code_len:21]
            elif code_len > 12 and code_len <= 14:
                vals['medicament_code'] = code_str[14 - code_len:21]
        return super(oehealth_medicament, self).create(cr, uid, vals, context)

    # def write(self, cr, uid, ids, vals, context=None):
    #     if context is None:
    #         context = {}
    #     medicaments_without_code = self.search(cr, uid, [('medicament_code', 'in', [False, '/']),('id', 'in', ids)], context=context)
    #     direct_write_ids = set(ids) - set(medicaments_without_code)
    #     super(oehealth_medicament, self).write(cr, uid, list(direct_write_ids), vals, context)
    #     for group_id in medicaments_without_code:
    #         val = self.pool.get('ir.sequence').get(cr, uid, 'oehealth.medicament.code')
    #         code = map(int, str(val))
    #         code_len = len(code)
    #         while len(code) < 14:
    #             code.insert(0, 0)
    #         while len(code) < 16:
    #             n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
    #             if n > 1:
    #                 f = 11 - n
    #             else:
    #                 f = 0
    #             code.append(f)
    #         code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
    #                                           str(code[2]) + str(code[3]) + str(code[4]),
    #                                           str(code[5]) + str(code[6]) + str(code[7]),
    #                                           str(code[8]) + str(code[9]) + str(code[10]),
    #                                           str(code[11]) + str(code[12]) + str(code[13]),
    #                                           str(code[14]) + str(code[15]))
    #         if code_len <= 3:
    #             vals['medicament_code'] = code_str[18 - code_len:21]
    #         elif code_len > 3 and code_len <= 6:
    #             vals['medicament_code'] = code_str[17 - code_len:21]
    #         elif code_len > 6 and code_len <= 9:
    #             vals['medicament_code'] = code_str[16 - code_len:21]
    #         elif code_len > 9 and code_len <= 12:
    #             vals['medicament_code'] = code_str[15 - code_len:21]
    #         elif code_len > 12 and code_len <= 14:
    #             vals['medicament_code'] = code_str[14 - code_len:21]
    #         super(oehealth_medicament, self).write(cr, uid, group_id, vals, context)
    #     return True

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

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

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

    def oehealth_medicament_okay(self, cr, uid, ids):
        self.write(cr, uid, ids, {'state': 'okay'})
        return True
        oldcertif = obj_module.search(cr, uid, [("certificate", "=", cert_num)])
        if oldcertif:
            raise osv.except_osv(_("Error !"), _("Certificate code Already Exists."))
        else:
            obj_module.write(cr, uid, module.id, {"certificate": cert_num})
        return True

    _name = "maintenance.maintenance.module"
    _description = "maintenance modules"
    _columns = {
        "name": fields.char("Name", size=128, required=True, readonly=False),
        "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",
Пример #26
0
class boilerplate_wizard(osv.osv_memory):
    _name = "boilerplate.wizard"
    _description = "Add Boilerplate"

    remote_name = _("Dummy")
    remote_model = "will.not.work"
    remote_note = "note"
    remote_product_id = False
    remote_partner_id = False

    def _lang_get(self, cr, uid, context={}):
        obj = self.pool.get('res.lang')
        ids = obj.search(cr, uid, [], context=context)
        res = obj.read(cr, uid, ids, ['code', 'name'], context)
        return [(r['code'], r['name']) for r in res] + [('', '')]

    _columns = {
        "boilerplate_id": fields.many2one("boilerplates.text", "Boilerplate"),
        "remote_id": fields.many2one(remote_model, "Remote model"),
        "lang": fields.selection(_lang_get, type='char', string="Language"),
    }

    def is_translateable(self, browse):
        # following a hint of Vo Minh Thu in https://bugs.launchpad.net/openobject-server/+bug/780584
        # it is still possible for a non-custom field to see if it is translatable by inspecting the _columns attribute of the model.
        if (browse):
            cols = getattr(browse, "_columns") or False
            remotefield = cols[self.remote_note] or False
            return (remotefield.translate)
        return False

    def browselanguages(self, cr, uid):
        res_lang = self.pool.get("res.lang")
        all_res_lang = res_lang.search(cr, uid, [])
        return res_lang.browse(cr, uid, all_res_lang)

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

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

            # look for wrongly chosen boilerplate
            bp_pid = session.boilerplate_id.product_id
            if (bp_pid):
                if (self.remote_product_id):
                    remote_pid = getattr(session.remote_id,
                                         self.remote_product_id)
                    if (not remote_pid or (bp_pid.id != remote_pid.id)):
                        raise osv.except_osv(
                            _('Product mismatch'),
                            _('Product set on the Boilerplate does not match this '
                              ) + self.remote_name)
                else:
                    raise osv.except_osv(
                        _('Product mismatch'),
                        _('Product set on the Boilerplate does not match this '
                          ) + self.remote_name)

            bp_pid = session.boilerplate_id.partner_id
            if (bp_pid):
                if (self.remote_partner_id):
                    remote_pid = getattr(session.remote_id,
                                         self.remote_partner_id)
                    if (not remote_pid or (bp_pid.id != remote_pid.id)):
                        raise osv.except_osv(
                            _('Partner mismatch'),
                            _('Partner set on the Boilerplate does not match this '
                              ) + self.remote_name)
                        return {'type': 'ir.actions.act_window_close'}
                else:
                    raise osv.except_osv(
                        _('Partner mismatch'),
                        _('Partner set on the Boilerplate does not match this '
                          ) + self.remote_name)
                    return {'type': 'ir.actions.act_window_close'}

            # ok, add notes, maybe per language
            remote_pool = self.pool.get(self.remote_model)

            if (self.is_translateable(session.remote_id)):
                # do the whole show, add accordingly in all translations

                # if no sublanguage defined, self.browse with context will return default language
                # means: If unset before, secondary language translations have double content:
                #   default language + translated entry.
                # Therefore, I test here if the default store matches
                default_notes_to_add = u""

                # get default language text
                for transession in self.browse(cr,
                                               uid, [session.id],
                                               context={}):
                    default_notes_to_add = unicode(
                        transession.boilerplate_id.text)

                    # if field was previously empty, first insert will put it to ALL databases.
                    oldnotes = getattr(transession.remote_id, self.remote_note)
                    if (not oldnotes):
                        remote_pool.write(
                            cr,
                            uid, [transession.remote_id.id],
                            {self.remote_note: default_notes_to_add},
                            context={})

                res_lang = self.pool.get('res.lang')
                lang_ids = res_lang.search(cr, uid, [])
                for lang in res_lang.browse(cr, uid, lang_ids):
                    ctx = context
                    ctx['lang'] = lang.code

                    for translated_session in self.browse(cr,
                                                          uid, [session.id],
                                                          context=ctx):
                        oldnotes = getattr(translated_session.remote_id,
                                           self.remote_note)

                        if (oldnotes):
                            oldnotes = oldnotes + "\n"
                        else:
                            oldnotes = str("").encode('utf-8')

                        notes_to_add = unicode(
                            translated_session.boilerplate_id.text)

                        # default_notes_to_add match old/last: bail out, already added default translation before
                        if (oldnotes.strip().endswith(default_notes_to_add)):
                            oldnotes = oldnotes[:oldnotes.
                                                rfind(default_notes_to_add)]

                        if (not oldnotes.strip().endswith(notes_to_add)):
                            newnotes = oldnotes + translated_session.boilerplate_id.text
                            remote_pool.write(
                                cr,
                                uid, [translated_session.remote_id.id],
                                {self.remote_note: newnotes},
                                context=ctx)

            else:
                # NOT self.is_translateable(session.remote_id) => use language as defined by current user

                ctx = context  # includes user default language
                # if language was set on wizard, use it
                if (session.lang):
                    ctx['lang'] = session.lang

                for translated_session in self.browse(cr,
                                                      uid, [session.id],
                                                      context=ctx):
                    oldnotes = getattr(session.remote_id, self.remote_note)
                    if (oldnotes):
                        oldnotes = oldnotes + "\n"
                    else:
                        oldnotes = str("").encode('utf-8')

                    notes_to_add = unicode(
                        translated_session.boilerplate_id.text)

                    if (not oldnotes.strip().endswith(notes_to_add)):
                        newnotes = oldnotes + translated_session.boilerplate_id.text
                        remote_pool.write(cr,
                                          uid, [session.remote_id.id],
                                          {self.remote_note: newnotes},
                                          context=context)

        return {'type': 'ir.actions.act_window_close'}
Пример #27
0
        user_obj = self.pool.get("res.users").browse(cr, uid, uid)
        google = self.pool.get("google.login")
        res = []
        try:
            gd_client = google.google_login(user_obj.gmail_user, user_obj.gmail_password, type="calendar")
            calendars = gd_client.GetAllCalendarsFeed()
            for cal in calendars.entry:
                res.append((cal.id.text, cal.title.text))
        except Exception, e:
            return [("failed", "Connection to google fail")]
        res.append(("all", "All Calendars"))
        return res

    _columns = {
        "create_partner": fields.selection(
            [("create_all", "Create partner for each contact"), ("create_address", "Import only address")], "Options"
        ),
        "customer": fields.boolean("Customer", help="Check this box to set newly created partner as Customer."),
        "supplier": fields.boolean("Supplier", help="Check this box to set newly created partner as Supplier."),
        "group_name": fields.selection(
            _get_group, "Group Name", help="Choose which group to import, By default it takes all."
        ),
        "calendar_name": fields.selection(_get_calendars, "Calendar Name"),
    }

    _defaults = {"create_partner": "create_all", "group_name": "all"}

    def import_google(self, cr, uid, ids, context=None):
        if context == None:
            context = {}
        if not ids:
class zoook_sync_product_image_wizard(osv.osv_memory):
    _name = 'zoook.sync.product.image.wizard'

    def _zoook_sale_shop(self, cr, uid, context=None):
        ids = self.pool.get('sale.shop').search(cr, uid, [('zoook_shop', '=', True)], order='id')
        shops = self.pool.get('sale.shop').read(cr, uid, ids, ['id','name'], context=context)
        return [(a['id'], a['name']) for a in shops]

    _columns = {
        'zoook_sale_shop': fields.selection(_zoook_sale_shop, 'Sale Shop', required=True),
        'result': fields.text('Result', readonly=True),
        'state':fields.selection([
            ('first','First'),
            ('done','Done'),
        ],'State'),
    }

    _defaults = {
        'state': lambda *a: 'first',
    }

    def sync_images(self, cr, uid, ids, data, context={}):
        """Export sync images"""

        if len(data['active_ids']) == 0:
            raise osv.except_osv(_('Error!'), _('Select Product Images to export'))

        form = self.browse(cr, uid, ids[0])
        shop = form.zoook_sale_shop
        shop = self.pool.get('sale.shop').browse(cr, uid, shop)

        product_ids = []
        for prod in self.pool.get('product.product').browse(cr, uid, data['active_ids']):
            product_available_shops = []
            for pshop in prod.product_tmpl_id.zoook_saleshop_ids:
                product_available_shops.append(pshop.id)

            if prod.product_tmpl_id.zoook_exportable and shop.id in product_available_shops:
                product_ids.append(prod.product_tmpl_id.id)

        values = {
            'state':'done',
        }
        if len(product_ids) > 0:
            values['result'] = '%s' % (', '.join(str(x) for x in product_ids))
        else:
            values['result'] = _('Not available some e-Sale Images Product to export')

        self.write(cr, uid, ids, values)

        cr.commit()

        if len(product_ids) > 0:
            values = {
                'ip': shop.zoook_ip,
                'port': shop.zoook_port,
                'username': shop.zoook_username,
                'password': shop.zoook_password,
                'key': shop.zoook_key,
                'ssh_key': shop.zoook_ssh_key,
                'basepath': shop.zoook_basepath,
            }

            context['command'] = 'sync/image.py -p %s' % (','.join(str(x) for x in product_ids))
            thread1 = threading.Thread(target=self.pool.get('sale.shop').zoook_export_images_thread, args=(cr.dbname, uid, shop.id, values, context))
            thread1.start()
        return True
Пример #29
0
            string='Latest version', type='char'),
        'latest_version': fields.char('Installed version', size=64, readonly=True),
        'published_version': fields.char('Published Version', size=64, readonly=True),

        'url': fields.char('URL', size=128, readonly=True),
        'sequence': fields.integer('Sequence'),
        'dependencies_id': fields.one2many('ir.module.module.dependency',
            'module_id', 'Dependencies', readonly=True),
        'auto_install': fields.boolean('Automatic Installation',
            help='An auto-installable module is automatically installed by the '
            'system when all its dependencies are satisfied. '
            'If the module has no dependency, it is always installed.'),
        'state': fields.selection([
            ('uninstallable','Not Installable'),
            ('uninstalled','Not Installed'),
            ('installed','Installed'),
            ('to upgrade','To be upgraded'),
            ('to remove','To be removed'),
            ('to install','To be installed')
        ], string='State', readonly=True, select=True),
        'demo': fields.boolean('Demo data', readonly=True),
        'license': fields.selection([
                ('GPL-2', 'GPL Version 2'),
                ('GPL-2 or any later version', 'GPL-2 or later version'),
                ('GPL-3', 'GPL Version 3'),
                ('GPL-3 or any later version', 'GPL-3 or later version'),
                ('AGPL-3', 'Affero GPL-3'),
                ('Other OSI approved licence', 'Other OSI Approved Licence'),
                ('Other proprietary', 'Other Proprietary')
            ], string='License', readonly=True),
        'menus_by_module': fields.function(_get_views, string='Menus', type='text', multi="meta", store=True),
        'reports_by_module': fields.function(_get_views, string='Reports', type='text', multi="meta", store=True),
class OemedicalPerinatal(osv.Model):

    _name = 'oemedical.perinatal'
    _description =  'Perinatal Information'
    _columns={
            'name' : fields.many2one('oemedical.patient', string='Perinatal Infomation'),
            'admission_code' : fields.char('Admission Code', size=64),
            'gravida_number' : fields.integer('Gravida #'),
            'abortion' : fields.boolean('Abortion'),
            'admission_date' : fields.datetime('Admission date', help="Date when she was admitted to give birth"),
            'prenatal_evaluations' : fields.integer('Prenatal evaluations', help="Number of visits to the doctor during pregnancy"),
            'start_labor_mode' : fields.selection([
                ('n', 'Normal'),
                ('i', 'Induced'),
                ('c', 'c-section'),
                ], 'Labor mode', select=True),
            'gestational_weeks' : fields.integer('Gestational weeks'),
            'gestational_days' : fields.integer('Gestational days'),
            'fetus_presentation' : fields.selection([
                            ('n', 'Correct'),
                            ('o', 'Occiput / Cephalic Posterior'),
                            ('fb', 'Frank Breech'),
                            ('cb', 'Complete Breech'),
                            ('t', 'Transverse Lie'),
                            ('t', 'Footling Breech'),
                            ], 'Fetus Presentation', select=True),
            'dystocia' : fields.boolean('Dystocia'),
            'laceration' : fields.selection([
                            ('perineal', 'Perineal'),
                            ('vaginal', 'Vaginal'),
                            ('cervical', 'Cervical'),
                            ('broad_ligament', 'Broad Ligament'),
                            ('vulvar', 'Vulvar'),
                            ('rectal', 'Rectal'),
                            ('bladder', 'Bladder'),
                            ('urethral', 'Urethral'),
                            ], 'Lacerations', sort=False),
            'hematoma' : fields.selection([
                            ('vaginal', 'Vaginal'),
                            ('vulvar', 'Vulvar'),
                            ('retroperitoneal', 'Retroperitoneal'),
                            ], 'Hematoma', sort=False),
            'placenta_incomplete' : fields.boolean('Incomplete Placenta'),
            'placenta_retained' : fields.boolean('Retained Placenta'),
            'abruptio_placentae' : fields.boolean('Abruptio Placentae', help='Abruptio Placentae'),
            'episiotomy' : fields.boolean('Episiotomy'),
            'vaginal_tearing' : fields.boolean('Vaginal tearing'),
            'forceps' : fields.boolean('Use of forceps'),
            'monitoring' : fields.one2many('oemedical.perinatal.monitor', 'name', string='Monitors'),
            'puerperium_monitor' : fields.one2many('oemedical.puerperium.monitor', 'name','Puerperium monitor'),
            'medications': fields.one2many('oemedical.patient.medication','patient_id', string='Medications',),
            'dismissed' : fields.datetime('Dismissed from hospital'),
            'place_of_death' : fields.selection([
                ('ho', 'Hospital'),
                ('dr', 'At the delivery room'),
                ('hh', 'in transit to the hospital'),
                ('th', 'Being transferred to other hospital'),
                ], 'Place of Death'),
            'mother_deceased' : fields.boolean('Deceased', help="Mother died in the process"),
            'notes' : fields.text('Notes'),
            }
Пример #31
0
class remesas_remesa(osv.osv):

    def _total(self, cr, uid, ids, prop, unknow_none,unknow_dict):
        id_set=",".join(map(str,ids))
        cr.execute("SELECT s.id,COALESCE(SUM(l.debit - l.credit),0) AS amount FROM remesas_remesa s LEFT OUTER JOIN account_move_line l ON (s.id=l.remesa_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ")
        res=dict(cr.fetchall())
        return res

    def _get_period(self, cr, uid, data, context={}):
        pool = pooler.get_pool(cr.dbname)
        ids = pool.get('account.period').find(cr, uid, context=context)
        period_id = False
        if len(ids):
            period_id = ids[0]
        return {'period_id': period_id}

    _name='remesas.remesa'
    _description='Remesas'
    _order = "name desc"
    _columns={ 
        'name': fields.char('Codigo de remesa', size=15),
        'cuenta_id': fields.many2one('remesas.cuenta','Cuenta de remesas', required=True, ),
        'total': fields.function(_total, method=True, string='Importe Total' ),
        'fecha': fields.date('Fecha'),
        'fecha_cargo': fields.date('Fecha Cargo (C19)'),
        'diario': fields.many2one('account.journal', 'Diario asiento cobro'),
        'account_id': fields.many2one('account.account', 'Cuenta asiento bancario', domain=[('type','<>','view'), ('type', '<>', 'closed')]),
        'receipts': fields.one2many('account.move.line', 'remesa_id' ,'Recibos', readonly=True, states={'draft':[('readonly',False)]}),
        'texto': fields.text('Texto para el banco'),
        'state': fields.selection( (('draft','Borrador'),('confirmed','Confirmada'),('2reconcile','A Conciliar'),('done','Realizada')), 'Estado', readonly=True),
        'agrupar_recibos': fields.boolean('Agrupar Recibos'),
        'asiento': fields.many2one('account.move', 'Asiento de Cobro', readonly=True),
        'fichero': fields.binary('Fichero para el banco', readonly=True),
    }

    _defaults={
        'fecha': lambda *a: time.strftime('%Y-%m-%d'),
        'fecha_cargo': lambda *a: time.strftime('%Y-%m-%d'),
        'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'remesas.sequence'),
        'state': lambda *a: 'draft'
    }

    def reset_efectos(self, cr, uid, ids):
        id_set=",".join(map(str,ids))
        logger.notifyChannel('ids', netsvc.LOG_INFO, str(id_set))

        for remesa in self.browse(cr,uid,ids,context={}):
            cr.execute("SELECT r.id FROM account_move_line r WHERE r.remesa_id = " + str(remesa.id))
            res=cr.fetchall()
            logger.notifyChannel('res', netsvc.LOG_INFO, res)
            for recibo in res:
                logger.notifyChannel('recibo', netsvc.LOG_INFO, recibo[0])
                logger.notifyChannel('remesa.recibo', netsvc.LOG_INFO, [6, 0, [x.id for x in remesa.receipts]][2])
#                logger.notifyChannel('remesas', netsvc.LOG_INFO, recibo[0])
        return True

    def add_receipts(self,cr,uid,id):
        pass

    def remove_receipt(self):
        pass

    def receipt_move(self):
        pass

    def remesa_move(self):
        pass

    def button_confirm(self, cr, uid, ids, context={}):
#        self.reset_efectos(cr,uid,ids)
        self._total
#        logger.notifyChannel('remesas', netsvc.LOG_INFO, 'Presionado botón Crear')
        tipo = self.browse(cr,uid,ids)[0].cuenta_id.tipo

        if tipo=='csb_19':    
#            logger.notifyChannel('remesas',netsvc.LOG_INFO, 'Tipo: csb_19')
            self.create_csb19(cr,uid,ids)
        elif tipo=='csb_58':
#            logger.notifyChannel('remesas',netsvc.LOG_INFO, 'Tipo: csb_58')
            self.create_csb58(cr,uid,ids)
        else:
#            logger.notifyChannel('remesas',netsvc.LOG_INFO, 'Tipo: ninguno')
            pass
        self.write(cr, uid, ids, {'state':'confirmed'})
        return True

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

    def button_contabilizar(self, cr, uid, ids, context={}):
        # Inicialización del objeto....
        rem = self.browse(cr,uid,ids)
        # Recuperamos algunos parámetros como el diario y el número de asiento asociado ¿Dejarlo al final?
        journal_id = rem[0]['diario'].id
        if not journal_id:
            raise osv.except_osv('Error del usuario', 'No se ha definido en la remesa el diario para el asiento del cobro.')
        journal = self.pool.get('account.journal').browse(cr,uid, journal_id)
        if journal.sequence_id:
            name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id)
        else:
            raise osv.except_osv('¡Asiento sin número !', '¡No se ha encontrado un numerador para esta secuencia!')

        # Inicialización de cuenta destino (de la cuenta bancaria), totalizador de importe y lineas de abono
#        logger.notifyChannel('remesas',netsvc.LOG_INFO, rem[0]['receipts'])
        dst_account_id = rem[0].account_id.id
        if not dst_account_id:
            raise osv.except_osv('Error del usuario', 'No se ha definido la cuenta contable del ingreso bancario para poder realizar el asiento del cobro.')
        importe_total = 0
        lines = []
        asientos_ids = ''
        # Iteramos por los distintos recibos asociados a la remesa...
        for recibo in rem[0]['receipts']:
            # Elegimos cuenta destino, segun cuenta asociada a recibo
            src_account_id = recibo.account_id.id

#            types = {'out_invoice': -1, 'in_invoice': 1, 'out_refund': 1, 'in_refund': -1}
            # Copiado de _pay_and_reconcile, del invoice.py
            direction = -1
            l1 = {
                'name': name,
                'debit': direction == 1 and (recibo.debit - recibo.credit),
                'credit': direction == -1 and (recibo.debit - recibo.credit),
                'amount_currency': 0,
                'account_id': src_account_id,
                'partner_id': recibo.partner_id['id'],
                'date': rem[0]['fecha_cargo'],
                'ref': recibo.ref,
            }

            importe_total += (recibo.debit - recibo.credit)
            lines.append((0,0,l1))
            asientos_ids += str(recibo.move_id.id) + ','
#            logger.notifyChannel('asientos',netsvc.LOG_INFO, asientos_ids)

        asientos_ids = asientos_ids.rstrip(',')    
        l2 = {
            'name':name,
            'debit': direction == -1 and importe_total,
            'credit': direction == 1 and importe_total,
            'amount_currency': 0,
            'account_id': dst_account_id,
            'partner_id': rem[0]['cuenta_id'].partner_id.id, # PRC
            #'partner_id': rem[0]['banco'].partner_id.id, 
            'date': rem[0]['fecha_cargo'],
        }
        lines.append((0, 0, l2))

#        logger.notifyChannel('lines',netsvc.LOG_INFO, lines)

        move = {'name': name, 'line_id': lines, 'journal_id':journal_id}
#        logger.notifyChannel('moves',netsvc.LOG_INFO, move)

        move_id = self.pool.get('account.move').create(cr, uid, move)
#        logger.notifyChannel('remesas',netsvc.LOG_INFO, recibo.id)
        self.write(cr,uid,ids, {'state':'2reconcile', 'asiento': move_id})
        return True


    def button_reconcile(self, cr, uid, ids, context={}):
        rem = self.browse(cr,uid,ids)
        move_id = rem[0]['asiento'].id
#        line_ids = []
#        asientos_ids = ''
#        src_account_ids = []
#        Para cada recibo de la remesa, localizamos el apunte del pago y conciliamos. Si no encontramos el pago, avisamos.
        line = self.pool.get('account.move.line')

        # Cuenta desajuste conciliación
        account_obj = self.pool.get('account.account')
        acc_ids = account_obj.search(cr, uid, [('code', '=like', '67800%0')])
        cuenta = acc_ids and acc_ids[0] or False
        if not cuenta:
            raise osv.except_osv('Error del usuario', 'No existe una cuenta con código 67800...0 para crear los asientos de desajuste.')

        # Diario desajuste conciliación
        journal_obj = self.pool.get('account.journal')
        jou_ids = journal_obj.search(cr, uid, [('name', 'ilike', '%general%')])
        diario = jou_ids and jou_ids[0] or False
        if not diario:
            raise osv.except_osv('Error del usuario', 'No existe un diario llamado ...general... donde crear los asientos de desajuste.')

        periodo =self._get_period(cr,uid,ids,context)['period_id']

        for recibo in rem[0]['receipts']:
            cr.execute('select id from account_move_line where move_id = '+str(move_id)+' and partner_id ='+str(recibo.partner_id.id)+' and ref= \''+str(recibo.ref)+'\' and debit = '+str(recibo.credit)+' and credit = '+str(recibo.debit)+' and state <> \''+str('reconciled')+'\' limit 1')
            lines = line.browse(cr, uid, map(lambda x: x[0], cr.fetchall()) )
            assert len(lines) == 1, "Error en el numero de recibos"
#            logger.notifyChannel('lines.id',netsvc.LOG_INFO, lines[0].id)
#            logger.notifyChannel('recibo.id',netsvc.LOG_INFO, recibo.id)
            self.pool.get('account.move.line').reconcile(cr, uid, [lines[0].id, recibo.id], 'remesa', cuenta, periodo, diario, context)

#            asientos_ids += str(recibo.move_id.id) + ','
#            if recibo.account_id.id not in src_account_ids:
#                src_account_ids.append(recibo.account_id.id)
#        asientos_ids = asientos_ids.rstrip(',')    
#        logger.notifyChannel('sql',netsvc.LOG_INFO, 'in '+str(move_id) + str(asientos_ids) )
#        for l in lines:
#            if l.account_id.id==src_account_id:
#                logger.notifyChannel('cuentas', netsvc.LOG_INFO, str(l.account_id.id) + '   ' +str(src_account_id) )
#                line_ids.append(l.id)
#            logger.notifyChannel('lineas',netsvc.LOG_INFO, line_ids)

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

        return True


    def digitos_cc(self, cc_in):
        "Quita los espacios en blanco del número de C.C. (por ej. los que pone el módulo digito_control_es)"
        cc = ""
        for i in cc_in:
            try:
                int(i)
                cc += i
            except ValueError:
                pass
        return cc


    def conv_ascii(self, text):
        "Convierte vocales accentuadas, ñ y ç a sus caracteres equivalentes ASCII"
        old_chars = ['á','é','í','ó','ú','à','è','ì','ò','ù','ä','ë','ï','ö','ü','â','ê','î','ô','û','Á','É','Í','Ú','Ó','À','È','Ì','Ò','Ù','Ä','Ë','Ï','Ö','Ü','Â','Ê','Î','Ô','Û','ñ','Ñ','ç','Ç']
        new_chars = ['a','e','i','o','u','a','e','i','o','u','a','e','i','o','u','a','e','i','o','u','A','E','I','O','U','A','E','I','O','U','A','E','I','O','U','A','E','I','O','U','n','N','c','C']
        for old, new in zip(old_chars, new_chars):
            text = text.replace(old, new)
        return text


    def create_csb19(self,cr,uid,ids):
        txt_remesa = ''
        rem = self.browse(cr,uid,ids)[0]

        # Comprobamos que exista número de C.C. y que tenga 20 dígitos
        if not rem.cuenta_id: 
            raise osv.except_osv('Error del usuario', 'El C.C. de la compañía %s no existe.' % rem.cuenta_id.nombre)

        cc = self.digitos_cc(rem.cuenta_id.banco_id.acc_number)
        if len(cc) != 20:
            raise osv.except_osv('Error del usuario', 'El número de C.C. de la compañía %s no tiene 20 dígitos.' % rem.cuenta_id.partner_id.name)
#        logger.notifyChannel('remesas',netsvc.LOG_INFO, str(rem))

        def _cabecera_presentador_19(self,texto):
            texto += '5180'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            date_now = now().strftime('%d%m%y')
            texto += date_now
            texto += 6*' '
            nombre = self.conv_ascii(rem.cuenta_id.nombre).decode('ascii', 'ignore')
            texto += nombre.ljust(40)
            texto += 20*' '
            texto += cc[0:8]
            texto += 66*' '
            texto += '\r\n'
#            logger.notifyChannel('cabecera presentador',netsvc.LOG_INFO, texto)
            return texto

        def _cabecera_ordenante_19(self,texto):
            texto += '5380'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            date_now = now().strftime('%d%m%y')
            texto += date_now
            date_cargo = mx.DateTime.strptime(rem.fecha_cargo,'%Y-%m-%d')
            texto += str(date_cargo.strftime('%d%m%y'))
            nombre = self.conv_ascii(rem.cuenta_id.nombre).decode('ascii', 'ignore')
            texto += nombre.ljust(40)
            texto += cc[0:20]
            texto += 8*' '
            texto += '01'
            texto += 64*' '
            texto += '\r\n'
            return texto

        def _individual_obligatorio_19(self,texto,recibo):
            # Comprobamos que exista número de C.C. y que tenga 20 dígitos
            if type(recibo['banco']) != str:
                raise osv.except_osv('Error del usuario', 'El número de C.C. del cliente %s no existe.' % recibo['nombre'])
            ccc = self.digitos_cc(recibo['banco'])
            if len(ccc) != 20:
                raise osv.except_osv('Error del usuario', 'El número de C.C. del cliente %s no tiene 20 dígitos.' % recibo['nombre'])

            texto += '5680'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += recibo['ref'].__str__().zfill(12)
            nombre = self.conv_ascii(recibo['nombre']).decode('ascii', 'ignore')
            texto += nombre[0:40].ljust(40)
            texto += ccc.__str__()[0:20].zfill(20)
            importe = int(round(recibo['importe']*100,0))
            texto += importe.__str__().zfill(10)
            texto += 16*' '
            texto += self.conv_ascii(recibo['concepto']).decode('ascii', 'ignore')[0:48].ljust(48)
            # Esto es lo convencional, descripción de 40 caracteres, pero se puede aprovechar los 8 espacios en blanco finales
            #texto += self.conv_ascii(recibo['concepto']).decode('ascii', 'ignore')[0:40].ljust(40)
            #texto += 8*' '
            texto += '\r\n'
            logger.notifyChannel('Individual obligatorio',netsvc.LOG_INFO, texto)
            return texto

        def _total_ordenante_19(self,texto):
            texto += '5880'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += 72*' '
            totalordenante = int(round(rem.total * 100,0))
            texto += totalordenante.__str__().zfill(10)
            texto += 6*' '
            ndomic = recibos.__len__()
#            logger.notifyChannel('Numero de recibos tot',netsvc.LOG_INFO, ndomic.__str__())
            texto += ndomic.__str__().zfill(10)
            texto += (ndomic + 2).__str__().zfill(10)
            texto += 38*' '
            texto += '\r\n'
            return texto

        def _total_general_19(self,texto):
            texto += '5980'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += 52*' '
            texto += '0001'
            texto += 16*' '
            totalremesa = int(round(rem.total * 100,0))
            texto += totalremesa.__str__().zfill(10)
            texto += 6*' '
            ndomic = recibos.__len__()
#            logger.notifyChannel('Numero de recibos tot',netsvc.LOG_INFO, ndomic.__str__())
            texto += ndomic.__str__().zfill(10)
            texto += (ndomic + 4).__str__().zfill(10)
            texto += 38*' '
            texto += '\r\n'
            return texto
            texto += '\r\n'
            return texto

        txt_remesa = _cabecera_presentador_19(self,txt_remesa)
        txt_remesa = _cabecera_ordenante_19(self,txt_remesa)
        if rem.agrupar_recibos == True: 
            #Nota: En la SELECT se ha eliminado (and b.active=True) ya que no existe el campo active
            cr.execute("""    SELECT
                                p.id as ref, 
                                p.name as nombre, 
                                b.acc_number as banco, 
                                sum(l.debit) - sum(l.credit) as importe,
                                'Fras: ' || min(l.ref) || ' -> ' || max(l.ref) as concepto
                            FROM 
                                account_move_line l 
                            LEFT OUTER JOIN 
                                res_partner_bank b 
                            ON 
                                l.acc_number=b.id 
                            LEFT OUTER JOIN
                                res_partner p 
                            ON
                                l.partner_id=p.id 
                            WHERE 
                                l.remesa_id=""" + str(rem.id)+ """
                            GROUP BY
                                p.id,
                                p.name,
                                b.acc_number""")
            recibos = cr.dictfetchall()

        else:
            #Nota: En la SELECT se ha eliminado (and b.active=True) ya que no existe el campo active
            cr.execute("""    SELECT
                                p.id as ref, 
                                p.name as nombre, 
                                b.acc_number as banco, 
                                l.debit as importe, 
                                'Factura ' || l.ref || '. ' || l.name as concepto 
                            FROM 
                                account_move_line l 
                            LEFT OUTER JOIN 
                                res_partner_bank b 
                            ON 
                                l.acc_number=b.id 
                            LEFT OUTER JOIN
                                res_partner p 
                            ON
                                l.partner_id=p.id 
                            WHERE 
                                l.remesa_id=""" + str(rem.id))
            recibos = cr.dictfetchall()

#        logger.notifyChannel('Numero de recibos',netsvc.LOG_INFO, recibos.__len__())

        for recibo in recibos:
#            logger.notifyChannel('recibo objeto...',netsvc.LOG_INFO, recibo)
            txt_remesa = _individual_obligatorio_19(self,txt_remesa,recibo)

        txt_remesa = _total_ordenante_19(self,txt_remesa)
        txt_remesa = _total_general_19(self,txt_remesa)
        self.write(cr, uid, ids, {'texto':txt_remesa, 'fichero':base64.encodestring(txt_remesa)})
#        logger.notifyChannel('remesas texto',netsvc.LOG_INFO, '\r\n' + txt_remesa)


    def create_csb58(self,cr,uid,ids):
        txt_remesa = ''
        rem = self.browse(cr,uid,ids)[0]
        # Comprobamos que exista número de C.C. y que tenga 20 dígitos
        if not rem.cuenta_id:
        #if not rem.banco: # PRC
            raise osv.except_osv('Error del usuario', 'El C.C. de la compañía %s no existe.' % rem.cuenta_id.nombre)
        cc = self.digitos_cc(rem.cuenta_id.banco_id.acc_number)
        if len(cc) != 20:
            raise osv.except_osv('Error del usuario', 'El número de C.C. de la compañía %s no tiene 20 dígitos.' % rem.cuenta_id.partner_id.name)
#        logger.notifyChannel('remesas',netsvc.LOG_INFO, str(rem))

        def _cabecera_presentador_58(self,texto):
            texto += '5170'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            date_now = now().strftime('%d%m%y')
            texto += date_now
            texto += 6*' '
            nombre = self.conv_ascii(rem.cuenta_id.nombre).decode('ascii', 'ignore')
            texto += nombre.ljust(40)
            texto += 20*' '
            texto += cc[0:8]
            texto += 66*' '
            texto += '\n'
#            logger.notifyChannel('cabecera presentador',netsvc.LOG_INFO, texto)
            return texto

        def _cabecera_ordenante_58(self,texto):
            texto += '5370'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            date_now = now().strftime('%d%m%y')
            texto += date_now
            texto += 6*' '
            nombre = self.conv_ascii(rem.cuenta_id.nombre).decode('ascii', 'ignore')
            texto += nombre.ljust(40)
            texto += cc[0:20]
            texto += 8*' '
            texto += '06'
            texto += 52*' '
            # Codigo INE de la plaza... en blanco...
            texto += 9*' '
            texto += 3*' '
            texto += '\n'
            return texto

        def _individual_obligatorio_58(self,texto,recibo):
            # Comprobamos que exista número de C.C. y que tenga 20 dígitos
            if type(recibo['banco']) != str:
                raise osv.except_osv('Error del usuario', 'El número de C.C. del cliente %s no existe.' % recibo['nombre'])
            ccc = self.digitos_cc(recibo['banco'])
            if len(ccc) != 20:
                raise osv.except_osv('Error del usuario', 'El número de C.C. del cliente %s no tiene 20 dígitos.' % recibo['nombre'])

            texto += '5670'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += recibo['ref'].__str__().zfill(12)
            nombre = self.conv_ascii(recibo['nombre']).decode('ascii', 'ignore')
            texto += nombre[0:40].ljust(40)
            texto += ccc.__str__()[0:20].zfill(20)
            importe = int(round(recibo['importe']*100,0))
            texto += importe.__str__().zfill(10)
            texto += 16*' '
            texto += self.conv_ascii(recibo['concepto']).__str__()[0:40].ljust(40)
            texto += recibo['vencimiento']
            texto += 2*' '
            texto += '\n'
#            logger.notifyChannel('Individual obligaotrio',netsvc.LOG_INFO, texto)
            return texto

        def _registro_obligatorio_domicilio_58(self,texto,recibo):
            texto += '5676'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += recibo['ref'].__str__().zfill(12)
            texto += self.conv_ascii(recibo['nombre']).ljust(40)
            texto += recibo['banco'].__str__()[0:20].zfill(20)
            importe = int(recibo['importe']*100)
            texto += importe.__str__().zfill(10)
            texto += 16*' '
            texto += self.conv_ascii(recibo['concepto']).__str__()[0:40].ljust(40)
            texto += recibo['vencimiento']
            texto += '  '
            texto += '\n'
#            logger.notifyChannel('Individual obligaotrio',netsvc.LOG_INFO, texto)
            return texto

        def _total_ordenante_58(self,texto):
            texto += '5870'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += 72*' '
            totalordenante = int(rem.total * 100)
            texto += totalordenante.__str__().zfill(10)
            texto += 6*' '
            ndomic = recibos.__len__()
#            logger.notifyChannel('Numero de recibos tot',netsvc.LOG_INFO, ndomic.__str__())
            texto += ndomic.__str__().zfill(10)
            texto += (ndomic + 2).__str__().zfill(10)
            texto += 38*' '
            texto += '\n'
            return texto

        def _total_general_58(self,texto):
            texto += '5970'
            texto += (rem.cuenta_id.partner_id.vat+rem.cuenta_id.sufijo).zfill(12)
            texto += 52*' '
            texto += '0001'
            texto += 16*' '
            totalremesa = int(round(rem.total * 100,0))
            texto += totalremesa.__str__().zfill(10)
            texto += 6*' '
            ndomic = recibos.__len__()
#            logger.notifyChannel('Numero de recibos tot',netsvc.LOG_INFO, ndomic.__str__())
            texto += ndomic.__str__().zfill(10)
            texto += (ndomic + 4).__str__().zfill(10)
            texto += 38*' '
            texto += '\n'
            return texto

        txt_remesa = _cabecera_presentador_58(self,txt_remesa)
        txt_remesa = _cabecera_ordenante_58(self,txt_remesa)
        if rem.agrupar_recibos == True:
            #Nota: En la SELECT se ha eliminado (and b.active=True) ya que no existe el campo active
            cr.execute("""    SELECT
                                p.id as ref, 
                                p.name as nombre, 
                                b.acc_number as banco, 
                                sum(l.debit) - sum(l.credit) as importe,
                                'Fras: ' || min(l.ref) || ' -> ' || max(l.ref) as concepto,
                                to_char(l.date_maturity, 'DDMMYY') as vencimiento
                            FROM 
                                account_move_line l 
                            LEFT OUTER JOIN 
                                res_partner_bank b 
                            ON 
                                l.acc_number=b.id 
                            LEFT OUTER JOIN
                                res_partner p 
                            ON
                                l.partner_id=p.id 
                            WHERE 
                                l.remesa_id=""" + str(rem.id)+ """
                            GROUP BY
                                p.id,
                                p.name,
                                b.acc_number,
                                vencimiento""")
            recibos = cr.dictfetchall()
        else:
            #Nota: En la SELECT se ha eliminado (and b.active=True) ya que no existe el campo active
            cr.execute("""    SELECT
                                p.id as ref, 
                                p.name as nombre, 
                                b.acc_number as banco, 
                                l.debit as importe, 
                                'Factura ' || l.ref || '. ' || l.name as concepto,
                                to_char(l.date_maturity, 'DDMMYY') as vencimiento
                            FROM 
                                account_move_line l 
                            LEFT OUTER JOIN 
                                res_partner_bank b 
                            ON 
                                l.acc_number=b.id 
                            LEFT OUTER JOIN
                                res_partner p 
                            ON
                                l.partner_id=p.id 
                            WHERE 
                                l.remesa_id=""" + str(rem.id))
            recibos = cr.dictfetchall()

#        logger.notifyChannel('Numero de recibos',netsvc.LOG_INFO, recibos.__len__())

        for recibo in recibos:
#            logger.notifyChannel('recibo objeto...',netsvc.LOG_INFO, recibo)
            if not recibo['vencimiento']:
                raise osv.except_osv('Error del usuario', 'Añada la fecha de vencimiento a todos los recibos')
            txt_remesa = _individual_obligatorio_58(self,txt_remesa,recibo)

        txt_remesa = _total_ordenante_58(self,txt_remesa)
        txt_remesa = _total_general_58(self,txt_remesa)
        self.write(cr, uid, ids, {'texto':txt_remesa, 'fichero':base64.encodestring(txt_remesa)})
Пример #32
0
class report_aeroo_import(osv.osv_memory):
    _name = 'aeroo.report_import'
    _description = 'Aeroo report import wizard'
    
    _columns = {
        'name':fields.char('Name', size=64),
        'file':fields.binary('Aeroo report file', filters='*.aeroo', required=True),
        'info': fields.text('Info', readonly=True),
        'state':fields.selection([
            ('draft','Draft'),
            ('info','Info'),
            ('done','Done'),
            
        ],'State', select=True, readonly=True),
                        
    }

    def default_get(self, cr, uid, fields_list, context=None):
        values = {'state': 'draft'}
        default_ids = context.get('default_ids')
        if default_ids:
            this = self.read(cr, uid, default_ids, ['name','state','file','info'], context=context)[0]
            del this['id']
            values.update(this)
        return values

    def install_report(self, cr, uid, ids, context=None):
        report_obj = self.pool.get('ir.actions.report.xml')
        this = self.browse(cr, uid, ids[0], context=context)
        if report_obj.search(cr, uid, [('report_name','=',this.name)], context=context):
            raise osv.except_osv(_('Warning!'), _('Report with service name "%s" already exist in system!') % this.name)
        fd = StringIO()
        fd.write(base64.decodestring(this.file))
        fd.seek(0)
        convert_xml_import(cr, 'report_aeroo', fd, {}, 'init', noupdate=True)
        fd.close()
        self.write(cr, uid, ids, {'state':'done'}, context=context)
        report_id = report_obj.search(cr, uid, [('report_name','=',this.name)], context=context)[-1]
        report = report_obj.browse(cr, uid, report_id, context=context)
        event_id = self.pool.get('ir.values').set_action(cr, uid, report.report_name, 'client_print_multi', report.model, 'ir.actions.report.xml,%d' % report_id)
        if report.report_wizard:
            report._set_report_wizard(report.id)

        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')

        mod_id = mod_obj.search(cr, uid, [('name', '=', 'action_aeroo_report_xml_tree')])[0]
        res_id = mod_obj.read(cr, uid, mod_id, ['res_id'])['res_id']
        act_win = act_obj.read(cr, uid, res_id, [])
        act_win['domain'] = [('id','=',report_id)]
        return act_win

    def next(self, cr, uid, ids, context=None):
        this = self.browse(cr, uid, ids[0], context=context)
        file_data = base64.decodestring(this.file)
        zip_stream = StringIO()
        zip_stream.write(file_data)
        zip_obj = zipfile.ZipFile(zip_stream, mode='r', compression=zipfile.ZIP_DEFLATED)
        if zipfile.is_zipfile(zip_stream):
            report_obj = self.pool.get('ir.actions.report.xml')
            context['allformats'] = True
            mimetypes = dict(report_obj._get_in_mimetypes(cr, uid, context=context))
            styles_select = dict(report_obj._columns['styles_mode'].selection)
            if 'data.xml' in zip_obj.namelist():
                data = zip_obj.read('data.xml')
            else:
                raise osv.except_osv(_('Error!'), _('Aeroo report file is invalid!'))
            tree = lxml.etree.parse(StringIO(data))
            root = tree.getroot()
            info = ''
            report = root.xpath("//data/record[@model='ir.actions.report.xml']")[0]
            style = root.xpath("//data/record[@model='report.stylesheets']")[0]
            rep_name = report.find("field[@name='name']").text
            rep_service = report.find("field[@name='report_name']").text
            rep_model = report.find("field[@name='model']").text
            rep_format = eval(report.find("field[@name='out_format']").attrib['search'], {})[0][2]
            rep_charset = report.find("field[@name='charset']").text
            parser_state = report.find("field[@name='parser_state']").text
            styles_mode = report.find("field[@name='styles_mode']").text
            tml_source = report.find("field[@name='tml_source']").text

            info += "Name: %s\n" % rep_name
            info += "Object: %s\n" % rep_model
            info += "Service Name: %s\n" % rep_service
            info += "Format: %s\n" % mimetypes.get(rep_format,'oo-odt')
            info += "Template: %s\n" % (tml_source=='parser' and 'defined by parser' or 'static')
            if rep_format=='genshi-raw':
                info += "Charset: %s\n" % rep_charset
            info += "Parser: %s\n" % (parser_state in ('def','loc') and 'customized' or 'default')
            info += "Stylesheet: %s%s\n" % (styles_select[styles_mode].lower(), style is not None and " (%s)" % style.find("field[@name='name']").text)
            self.write(cr, uid, ids, {'name':rep_service,'info':info,'state':'info','file':base64.encodestring(data)}, context=context)
        else:
            raise osv.except_osv(_('Error!'), _('Is not Aeroo report file.'))

        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')

        mod_id = mod_obj.search(cr, uid, [('name', '=', 'action_aeroo_report_import_wizard')])[0]
        res_id = mod_obj.read(cr, uid, mod_id, ['res_id'])['res_id']
        act_win = act_obj.read(cr, uid, res_id, [])
        act_win['domain'] = [('id','in',ids)]
        act_win['context'] = {'default_ids':ids}
        return act_win
        
    _defaults = {
        'state': 'draft',
    }
Пример #33
0
            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),
    }

    _defaults = {
        'user_id': lambda self,cr,uid,ctx:uid,
        'file_size': lambda self,cr,uid,ctx:0,
        'store_method': lambda *args: 'db'
    }
    _sql_constraints = [
        ('filename_uniq', 'unique (name,parent_id,res_id,res_model)', 'The file name must be unique !')
Пример #34
0
    def _get_calendars(self, cr, uid, context=None):
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        google = self.pool.get('google.login')
        res = []
        try:
            gd_client = google.google_login(user_obj.gmail_user, user_obj.gmail_password, type='calendar')
            calendars = gd_client.GetAllCalendarsFeed()
            for cal in calendars.entry:
                res.append((cal.id.text, cal.title.text))
        except Exception, e:
            return [('failed', 'Connection to google fail')]
        res.append(('all', 'All Calendars'))
        return res

    _columns = {
        'create_partner': fields.selection([('create_all','Create partner for each contact'),('create_address','Import only address')],'Options'),
        'customer': fields.boolean('Customer', help="Check this box to set newly created partner as Customer."),
        'supplier': fields.boolean('Supplier', help="Check this box to set newly created partner as Supplier."),
        'group_name': fields.selection(_get_group, "Group Name", size=32,help="Choose which group to import, By default it takes all."),
        'calendar_name': fields.selection(_get_calendars, "Calendar Name", size=32),
     }

    _defaults = {
        'create_partner': 'create_all',
        'group_name': 'all',
        'calendar_name': 'all',
    }

    def import_google(self, cr, uid, ids, context=None):
        if context == None:
            context = {}
Пример #35
0
            cr.execute('update sync_server_entity_activity set datetime=%s, activity=%s where entity_id=%s', (now, activity, entity.id))
        except psycopg2.OperationalError, e:
            if not wait and e.pgcode == '55P03':
                # can't acquire lock: ok the show must go on
                cr.execute("ROLLBACK TO update_entity_last_activity")
                logging.getLogger('sync.server').info("Can't acquire lock to set last_activity")
                return
            raise

    _columns = {
        'name':fields.char('Instance Name', size=64, required=True, select=True),
        'identifier':fields.char('Identifier', size=64, readonly=True, select=True),
        'hardware_id' : fields.char('Hardware Identifier', size=128, select=True),
        'parent_id':fields.many2one('sync.server.entity', 'Parent Instance', ondelete='cascade'),
        'group_ids':fields.many2many('sync.server.entity_group', 'sync_entity_group_rel', 'entity_id', 'group_id', string="Groups"),
        'state' : fields.selection([('pending', 'Pending'), ('validated', 'Validated'), ('invalidated', 'Invalidated'), ('updated', 'Updated')], 'State'),
        'email':fields.char('Contact Email', size=512),
        'user_id': fields.many2one('res.users', 'User', ondelete='restrict', required=True),
        
        #just in case, since the many2one exist it has no cost in database
        'children_ids' : fields.one2many('sync.server.entity', 'parent_id', 'Children Instances'),
        'update_token' : fields.char('Update security token', size=256),

        'activity' : fields.function(_get_activity, type='char', string="Activity", method=True, multi="_get_act"),
        'last_dateactivity': fields.function(_get_activity, type='datetime', string="Date of last activity", method=True, multi="_get_act"),
        #'last_activity' : fields.datetime("Date of last activity", readonly=True),

        'parent_left' : fields.integer("Left Parent", select=1),
        'parent_right' : fields.integer("Right Parent", select=1),
        
        'msg_ids_tmp':fields.text('List of temporary ids of message to be pulled'),
Пример #36
0
                                input_model[ir_model_field.name]

                record_dict['fields'] = field_dict
                data_json.append(record_dict)

        out = base64.encodestring(json.dumps(data_json, indent=4))

        return self.write(cr, uid, ids, {
            'state': 'done', 'dm_export_data_wizard_data': out,
            'name': json_exported_file_name
        }, context=context)

    EXPORT_TYPE = (('a', 'based on model'), ('b', 'based on module'))

    _columns = {
        'name': fields.char('Filename', size=128, readonly=True),
        'dm_export_data_wizard_type': fields.selection(EXPORT_TYPE,
            'DM Export Data Wizard Type'),
        'ir_model_id': fields.many2one('ir.model', 'IR Model'),
        'ir_module_module_id': fields.many2one('ir.module.module',
                                               'IR Module Module'),
        'dm_export_data_wizard_data': fields.binary('Export Data Wizard Data',
                                                 readonly=True),
        'state': fields.selection([('init', 'init'), ('done', 'done')],
                                  'state', readonly=True),
    }

    _defaults = {'state': 'init', 'dm_export_data_wizard_type': 'a'}

DmExportDataWizard()
Пример #37
0
class perintah_kerja(osv.osv):
    _name = "perintah.kerja"
    _columns = {
        'name':
        fields.char('Work Order',
                    required=True,
                    size=64,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'date':
        fields.date('Order Date',
                    required=True,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'type':
        fields.selection([('other', 'Others'), ('pabrikasi', 'Pabrikasi'),
                          ('man', 'Man Power'), ('service', 'Service')],
                         'Type',
                         readonly=True,
                         states={'draft': [('readonly', False)]}),
        'sale_id':
        fields.many2one('sale.order',
                        'Sale Order',
                        required=False,
                        readonly=True,
                        domain=[('state', 'in', ('progress', 'manual'))],
                        states={'draft': [('readonly', False)]}),
        'partner_id':
        fields.many2one('res.partner',
                        'Customer',
                        domain=[('customer', '=', True)],
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'kontrak':
        fields.char('Contract No',
                    size=64,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'kontrakdate':
        fields.date('Contract Date',
                    required=True,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'workshop':
        fields.char('Working Place',
                    size=64,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        'state':
        fields.selection([('draft', 'Draft'), ('approve', 'Approved'),
                          ('done', 'Done'), ('cancel', 'Cancel')],
                         'State',
                         readonly=True),
        'perintah_lines':
        fields.one2many('perintah.kerja.line',
                        'perintah_id',
                        'Work Lines',
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'material_lines':
        fields.one2many('raw.material.line',
                        'perintah_id',
                        'Material Consumption',
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'delivery_date':
        fields.date('Delivery Date',
                    required=False,
                    readonly=True,
                    states={'draft': [('readonly', False)]}),
        '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),
        'creator':
        fields.many2one('res.users', 'Created by'),
        'checker':
        fields.many2one('res.users', 'Checked by'),
        'approver':
        fields.many2one('res.users', 'Approved by'),
        'note':
        fields.text('Notes'),
        'terms':
        fields.text('Terms & Condition'),
        'location_src_id':
        fields.many2one('stock.location',
                        'Raw Materials Location',
                        required=True,
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
        'location_dest_id':
        fields.many2one('stock.location',
                        'Finished Products Location',
                        required=True,
                        readonly=True,
                        states={'draft': [('readonly', False)]}),
    }

    _defaults = {
        'name': '/',
        'note': '-',
        'type': 'pabrikasi',
        'state': 'draft',
        'location_src_id': 14,
        'location_dest_id': 14,
        'date': time.strftime('%Y-%m-%d'),
        'kontrakdate': time.strftime('%Y-%m-%d'),
    }

    _order = "name desc"

    def create(self, cr, uid, vals, context=None):
        # print vals
        if vals['special'] == True:
            person = self.pool.get('res.users').browse(cr, uid, uid)
            rom = [
                0, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X',
                'XI', 'XII'
            ]
            # usa = 'SPC'
            usa = str(
                self.pool.get('pr').browse(cr, uid,
                                           vals['pr_id']).salesman_id.initial)
            val = self.pool.get('ir.sequence').get(cr, uid,
                                                   'perintah.kerja').split('/')
            use = str(person.initial)
            vals['creator'] = person.id
            vals['name'] = val[
                -1] + 'A/SBM-ADM/' + usa + '-' + use + '/' + rom[int(
                    val[2])] + '/' + val[1]
            return super(perintah_kerja, self).create(cr,
                                                      uid,
                                                      vals,
                                                      context=context)
        else:
            person = self.pool.get('res.users').browse(cr, uid, uid)
            rom = [
                0, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X',
                'XI', 'XII'
            ]
            usa = str(
                self.pool.get('sale.order').browse(
                    cr, uid, vals['sale_id']).user_id.initial)
            val = self.pool.get('ir.sequence').get(cr, uid,
                                                   'perintah.kerja').split('/')
            use = str(person.initial)
            vals['creator'] = person.id
            vals['name'] = val[
                -1] + 'A/SBM-ADM/' + usa + '-' + use + '/' + rom[int(
                    val[2])] + '/' + val[1]
            return super(perintah_kerja, self).create(cr,
                                                      uid,
                                                      vals,
                                                      context=context)

        # oldd
        # person = self.pool.get('res.users').browse(cr, uid, uid)
        # rom = [0, 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII']
        # usa = str(self.pool.get('sale.order').browse(cr, uid, vals['sale_id']).user_id.initial)
        # val = self.pool.get('ir.sequence').get(cr, uid, 'perintah.kerja').split('/')
        # use = str(person.initial)
        # vals['creator'] = person.id
        # vals['name'] = val[-1]+'A/SBM-ADM/'+usa+'-'+use+'/'+rom[int(val[2])]+'/'+val[1]
        # return super(perintah_kerja, self).create(cr, uid, vals, context=context)
        # return False

    def sale_change(self, cr, uid, ids, sale):
        if sale:
            res = {}
            line = []
            obj_sale = self.pool.get('sale.order').browse(cr, uid, sale)
            for x in obj_sale.order_line:
                line.append({
                    'product_id': x.product_id.id,
                    'product_qty': x.product_uom_qty,
                    'product_uom': x.product_uom.id,
                    'name': x.name
                    # 'name': '['+str(x.product_id.code)+']' + ' ' + x.product_id.name
                })

            res['perintah_lines'] = line
            res['kontrak'] = obj_sale.client_order_ref
            res['partner_id'] = obj_sale.partner_id.id
            res['kontrakdate'] = obj_sale.date_order
            res['delivery_date'] = obj_sale.delivery_date

            return {'value': res}
        return True

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

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

    def work_confirm(self, cr, uid, ids, context=None):
        val = self.browse(cr, uid, ids)[0]
        if not val.perintah_lines:
            raise osv.except_osv(('Perhatian !'),
                                 ('Tabel work line harus diisi !'))
        self.write(
            cr, uid, ids, {
                'state': 'approve',
                'checker': self.pool.get('res.users').browse(cr, uid, uid).id
            })
        return True

    def work_validate(self, cr, uid, ids, context=None):
        val = self.browse(cr, uid, ids, context={})[0]
        if val.type == 'pabrikasi':
            seq_out_mnfct = self.pool.get('ir.sequence').get(
                cr, uid, 'stock.picking.out.manufacture')
            seq_from_mnfct = self.pool.get('ir.sequence').get(
                cr, uid, 'stock.picking.from.manufacture')

            if not seq_out_mnfct:
                raise osv.except_osv(
                    _('Error'),
                    _('stock.picking.out.manufacture Sequence not exist.\nPlease contact system administrator'
                      ))

            if not seq_from_mnfct:
                raise osv.except_osv(
                    _('Error'),
                    _('stock.picking.from.manufacture Sequence not exist.\nPlease contact system administrator.'
                      ))

            material_id = self.pool.get('stock.picking').create(
                cr, uid, {
                    'name': seq_out_mnfct,
                    'origin': val.name,
                    'type': 'internal',
                    'move_type': 'one',
                    'state': 'draft',
                    'date': val.date,
                    'auto_picking': True,
                    'company_id': 1,
                })

            goods_id = self.pool.get('stock.picking').create(
                cr, uid, {
                    'name': seq_from_mnfct,
                    'origin': val.name,
                    'type': 'internal',
                    'move_type': 'one',
                    'state': 'draft',
                    'date': val.date,
                    'auto_picking': True,
                    'company_id': 1,
                })

            for x in val.material_lines:
                self.pool.get('stock.move').create(
                    cr, uid, {
                        'name':
                        x.product_id.default_code + x.product_id.name_template,
                        'picking_id': material_id,
                        'product_id': x.product_id.id,
                        'product_qty': x.product_qty,
                        'product_uom': x.product_uom.id,
                        'date': val.date,
                        'location_id': val.location_src_id.id,
                        'location_dest_id': 7,
                        'state': 'waiting',
                        'company_id': 1
                    })
            prodlot = self.pool.get('stock.production.lot')
            for x in val.perintah_lines:
                prodlot_obj_id = False
                if x.product_id.track_production:
                    # check if manufacture lot exists
                    lot_name_ws = x.product_id.default_code + '-WS'
                    get_lot = prodlot.search(
                        cr, uid, [('product_id', '=', x.product_id.id),
                                  ('name', '=', lot_name_ws)])
                    if not get_lot:
                        # set new serial
                        prodlot_obj_id = prodlot.create(
                            cr,
                            uid, {
                                'name': lot_name_ws,
                                'product_id': x.product_id.id,
                                'desc': 'Manufacture Lot',
                            },
                            context=context)
                    else:
                        prodlot_obj_id = get_lot[0]

                    # set serial number for manufacture lot
                print prodlot_obj_id, ">>>>>>>>>>>>>>"

                self.pool.get('stock.move').create(
                    cr, uid, {
                        'name':
                        x.product_id.default_code + x.product_id.name_template,
                        'picking_id': goods_id,
                        'product_id': x.product_id.id,
                        'product_qty': x.product_qty,
                        'product_uom': x.product_uom.id,
                        'date': val.date,
                        'location_id': 7,
                        'location_dest_id': val.location_dest_id.id,
                        'state': 'waiting',
                        'company_id': 1,
                        'prodlot_id': prodlot_obj_id or False
                    })

            wf_service = netsvc.LocalService("workflow")
            wf_service.trg_validate(uid, 'stock.picking', goods_id,
                                    'button_confirm', cr)
            wf_service.trg_validate(uid, 'stock.picking', material_id,
                                    'button_confirm', cr)

            self.pool.get('stock.picking').force_assign(
                cr, uid, [goods_id, material_id], context)

        self.write(
            cr, uid, ids, {
                'state': 'done',
                'approver': self.pool.get('res.users').browse(cr, uid, uid).id
            })
        return True

    def unlink(self, cr, uid, ids, context=None):
        val = self.browse(cr, uid, ids, context={})[0]
        if val.state != 'draft':
            raise osv.except_osv(
                ('Invalid action !'),
                ('Cannot delete a work order which is in state \'%s\'!') %
                (val.state, ))
        return super(perintah_kerja, self).unlink(cr,
                                                  uid,
                                                  ids,
                                                  context=context)

    def print_perintah(self, cr, uid, ids, context=None):
        data = {}
        val = self.browse(cr, uid, ids)[0]
        data['form'] = {}
        data['ids'] = context.get('active_ids', [])
        data['form']['data'] = self.read(cr, uid, ids)[0]

        qty = ''
        product = ''
        for x in val.perintah_lines:
            qty = qty + str(x.product_qty) + ' ' + x.product_uom.name + '\n\n'
            product = product + x.name + '\n\n'

        product = product + '\n\n' + val.note

        data['form']['data']['qty'] = qty
        data['form']['data']['product'] = product
        data['form']['data']['creator'] = val.creator.name
        data['form']['data']['checker'] = val.checker.name
        data['form']['data']['approver'] = val.approver.name

        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'perintah.A4',
            'datas': data,
            'nodestroy': True
        }
class valid_stock_moves(osv.osv):
    """View that filter stock_moves by not state = 'cancel' Use this view to show traceability tree"""
    _name = "valid.stock.moves"
    _auto = False

    def _get_simplified_trace_up(self, cr, uid, ids, field_name, arg, context):
        """get the last childs moves for a specific move"""
        res = {}
        for move in self.browse(cr, uid, ids):
            cr.execute("select id from stock_move_parents(%s)", (move.id, ))
            records = []
            for record in cr.fetchall():
                records.append(record[0])
            if records[0] in ids:
                res[move.id] = []
            else:
                res[move.id] = records
        return res

    def _get_simplified_trace_down(self, cr, uid, ids, field_name, arg,
                                   context):
        """get the top parents moves for a specific move"""
        res = {}
        for move in self.browse(cr, uid, ids):
            cr.execute("select id from stock_move_childs(%s)", (move.id, ))
            records = []
            for record in cr.fetchall():
                records.append(record[0])
            if records[0] in ids:
                res[move.id] = []
            else:
                res[move.id] = records
        return res

    def _get_move_type(self, cr, uid, ids, field_name, arg, context={}):
        """get the type of move for do more accessibly traceability tree"""
        return self.pool.get('stock.move').get_move_type(cr,
                                                         uid,
                                                         ids,
                                                         context=context)

    _columns = {
        'id':
        fields.integer('id', readonly=True),
        'name':
        fields.char('Name', size=64, readonly=True, select=True),
        'product_id':
        fields.many2one('product.product',
                        'Product',
                        readonly=True,
                        select=True),
        'product_qty':
        fields.float('Quantity', readonly=True),
        'product_uom':
        fields.many2one('product.uom',
                        'Product UOM',
                        readonly=True,
                        select=True),
        'prodlot_id':
        fields.many2one('stock.production.lot',
                        'Production Lot',
                        readonly=True,
                        select=True),
        'expiry_date':
        fields.datetime('Expiry Date', readonly=True),
        'supplier':
        fields.char('Supplier', size=64, readonly=True),
        'tracking_id':
        fields.many2one('stock.tracking', 'Pack', select=True, readonly=True),
        'product_packaging':
        fields.many2one('product.packaging',
                        'Packaging',
                        readonly=True,
                        select=True),
        'picking_id':
        fields.many2one('stock.picking',
                        'Packing List',
                        readonly=True,
                        select=True),
        'location_id':
        fields.many2one('stock.location',
                        'Location',
                        readonly=True,
                        select=True),
        'location_dest_id':
        fields.many2one('stock.location',
                        'Dest. Location',
                        readonly=True,
                        select=True),
        'date':
        fields.datetime('Date Created', readonly=True),
        'date_expected':
        fields.datetime('Date', readonly=True),
        'state':
        fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'),
                          ('confirmed', 'Not Available'),
                          ('assigned', 'Available'), ('done', 'Done'),
                          ('cancel', 'Cancelled')],
                         'State',
                         size=12,
                         readonly=True),
        'move_history_simplified_up':
        fields.function(_get_simplified_trace_up,
                        method=True,
                        relation='stock.move',
                        type="many2many",
                        string='Traceability simplified upstream'),
        'move_history_simplified_down':
        fields.function(_get_simplified_trace_down,
                        method=True,
                        relation='stock.move',
                        type="many2many",
                        string='Traceability simplified downstream'),
        'move_history_ids':
        fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id',
                         'child_id', 'Move History'),
        'move_history_ids2':
        fields.many2many('stock.move', 'stock_move_history_ids', 'child_id',
                         'parent_id', 'Move History'),
        'move_type':
        fields.function(_get_move_type,
                        method=True,
                        string='Type',
                        type="char",
                        size=24,
                        readonly=True),
        'production_id':
        fields.many2one('mrp.production',
                        'Production',
                        readonly=True,
                        select=True)
    }

    def init(self, cr):
        """creates view when install"""
        cr.execute("""
            create or replace view valid_stock_moves as (
                select stock_move.id as id,stock_move.name as name,stock_move.product_id as product_id,product_qty,product_uom,prodlot_id,stock_production_lot.life_date as expiry_date,
                    supplier,tracking_id,product_packaging,picking_id,location_id,location_dest_id,stock_move.date as date,
                    date_expected,state,production_id
                from stock_move left join stock_production_lot on stock_move.prodlot_id = stock_production_lot.id
                where state not in ('cancel')
            )""")

    def unlink(self, cr, uid, ids, context={}):
        """not can delete, beacause is database view"""
        raise osv.except_osv(_('Error !'), _('You cannot delete any record!'))
Пример #39
0
    def _payment_type_name_get(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for rec in self.browse(cr, uid, ids, context):
            result[rec.id] = rec.mode and rec.mode.type.name or ""
        return result

    def _name_get(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for rec in self.browse(cr, uid, ids, context):
            result[rec.id] = rec.reference
        return result

    _columns = {
        'type': fields.selection([
            ('payable','Payable'),
            ('receivable','Receivable'),
            ],'Type', readonly=True, select=True),
        # invisible field to filter payment order lines by payment type
        'payment_type_name': fields.function(_payment_type_name_get, method=True, type="char", size=64, string="Payment type name"),
        # The field name is necessary to add attachement documents to payment orders
        'name': fields.function(_name_get, method=True, type="char", size=64, string="Name"),
        'create_account_moves': fields.selection([('bank-statement','Bank Statement'),('direct-payment','Direct Payment')],
                                                 'Create Account Moves',
                                                 required=True,
                                                 states={'done':[('readonly',True)]},
                                                 help='Indicates when account moves should be created for order payment lines. "Bank Statement" '\
                                                      'will wait until user introduces those payments in bank a bank statement. "Direct Payment" '\
                                                      'will mark all payment lines as payied once the order is done.'),
        'period_id': fields.many2one('account.period', 'Period', states={'done':[('readonly',True)]}),
    }
    _defaults = {
class bj_assessment_window(osv.osv):
    _name = 'bj.assessment.window'

    def on_change_confirm_bj(self, cr, uid, ids, context=None):
        invoice_ids = []
        for key in self.browse(cr, uid, ids, context=context):
            reg_no = key.reg_no
            output = key.wakf_id.id
            bj_line_id = key.bj_line_id
            for bj_line in key.bj_line_id:
                product_id = 3
                name = "BJ"
                quantity = 1
                price_subtotal = bj_line.net_income1
                price_unit = bj_line.net_income1
                new_amount = bj_line.net_income1
                acc_year = bj_line.account_year_line.id
                invoice_ids.append((0, 0, {
                    'product_id': product_id,
                    'name': name,
                    'quantity': quantity,
                    'price_subtotal': price_subtotal,
                    'price_unit': price_unit,
                    'new_amount': new_amount
                }))
                self.pool.get('account.invoice').create(
                    cr, uid, {
                        'is_assessment': True,
                        'registration_no': reg_no,
                        'account_id': 1,
                        'journal_id': '1',
                        'partner_id': output,
                        'invoice_line': invoice_ids,
                        'assess_year_saleorder': acc_year,
                        'assessment_type': 'bj'
                    })
                invoice_ids = []
            self.write(cr, uid, ids, {'state': 'approved'})
        return False

    def _total_amount_net_bj(self,
                             cr,
                             uid,
                             ids,
                             field_name,
                             arg,
                             context=None):
        val1 = 0
        res = {}
        for order in self.browse(cr, uid, ids, context=context):
            res[order.id] = {
                'total_income': 0,
            }
            for line in order.bj_line_id:
                val1 += line.net_income1
            res[order.id]['net_income'] = val1
        return res

    def _total_amount_net_Assess(self,
                                 cr,
                                 uid,
                                 ids,
                                 field_name,
                                 arg,
                                 context=None):
        val1 = 0
        res = {}
        for order in self.browse(cr, uid, ids, context=context):
            res[order.id] = {
                'total_income': 0,
            }
            for line in order.bj_line_id:
                val1 += line.assess_amount
            res[order.id]['net_income_assess'] = val1
        return res

    def _total_amount_contribution_bj(self,
                                      cr,
                                      uid,
                                      ids,
                                      field_name,
                                      arg,
                                      context=None):
        val1 = 0
        res = {}
        for order in self.browse(cr, uid, ids, context=context):
            res[order.id] = {
                'total_income': 0,
            }
            for line in order.bj_line_id:
                val1 += line.contri_amount1
            res[order.id]['contri_amount'] = val1
        return res

    def _deflt_ass_year(self, cr, uid, ids, context=None):
        res = {}
        today = date.today()
        month_of = today.month
        if month_of <= 3:
            date_of = '%d-%d' % (today.year - 1, today.year)
        if month_of >= 4:
            date_of = '%d-%d' % (today.year, today.year + 1)
        search_condition = [('name', '=', date_of)]
        search_ids = self.pool.get('account.fiscalyear').search(
            cr, uid, search_condition, context=context)
        if search_ids:
            similar_objs = self.pool.get('account.fiscalyear').browse(
                cr, uid, search_ids, context=context)
            return similar_objs[0].id

    def action_approve(self, cr, uid, ids, context=None):
        follow_list = []
        dicto = {}
        for rec in self.browse(cr, uid, ids, context=context):
            dicto = {
                'name': "Approved",
                'who': uid,
                'when': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            }
            follow_list.append((0, 0, dicto))
            self.write(cr, uid, ids, {
                'state': 'approved',
                'follow_line_id': follow_list
            })
        return True

    def action_send(self, cr, uid, ids, context=None):
        follow_list = []
        dicto = {}
        invoice_ids = []
        for rec in self.browse(cr, uid, ids, context=context):
            dicto = {
                'name': "BJ Send",
                'who': uid,
                'when': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            }
            follow_list.append((0, 0, dicto))
            price_unit_income = rec.net_bj or False
            new_amount_income = rec.net_bj or False
            output = rec.wakf_id.id or False
            acc_year = rec.account_year.id or False
            ass_year = rec.assessment_year.id or False
            reg_no = rec.reg_no or False
            ##############################################################################################################
            search_ids = self.pool.get('product.product').search(
                cr, uid, [('name', '=', "BJ")])
            if not search_ids:
                raise osv.except_osv(_('Warning!'),
                                     _('Please create a "BJ" property first'))
            income_id = self.pool.get('product.product').browse(
                cr, uid, search_ids)[0].id

            search_ids = self.pool.get('account.account').search(
                cr, uid, [('name', '=', "Accounts Receivable")])
            if not search_ids:
                raise osv.except_osv(
                    _('Warning!'),
                    _('Please create an account "Accounts Receivable" first'))
            account_id = self.pool.get('account.account').browse(
                cr, uid, search_ids)[0].id

            search_ids = self.pool.get('account.journal').search(
                cr, uid, [('name', '=', "Assessment Journal")])
            if not search_ids:
                raise osv.except_osv(
                    _('Warning!'),
                    _('Please create "Assessment Journal" First'))
            journal_id = self.pool.get('account.journal').browse(
                cr, uid, search_ids)[0].id
            ##############################################################################################################
            invoice_ids.append((0, 0, {
                'product_id': income_id,
                'name': "BJ Assessment",
                'quantity': 1,
                'price_unit': price_unit_income,
                'new_amount': new_amount_income,
                'sws': False
            }))  # sws =True, 7% calculation disabled
            self.pool.get('account.invoice').create(
                cr, uid, {
                    'registration_no': reg_no,
                    'assess_year_saleorder': acc_year,
                    'account_year_saleorder': ass_year,
                    'is_assessment': True,
                    'appli_no': False,
                    'account_id': account_id,
                    'journal_id': journal_id,
                    'partner_id': output,
                    'invoice_line': invoice_ids,
                    'total_income_saleorder': False,
                    'total_expense_saleorder': False,
                    'assessment_type': 'bj'
                })
        self.write(cr, uid, ids, {
            'state': 'send',
            'follow_line_id': follow_list
        })
        return True

    def action_cancel(self, cr, uid, ids, context=None):
        follow_list = []
        dicto = {}
        for rec in self.browse(cr, uid, ids, context=context):
            dicto = {
                'name': "BJ Cancelled",
                'who': uid,
                'when': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            }
            follow_list.append((0, 0, dicto))
            self.write(cr, uid, ids, {
                'state': 'cancelled',
                'follow_line_id': follow_list
            })
        return True

    def action_re_assessment(self, cr, uid, ids, context=None):
        follow_list = []
        dicto = {}
        for rec in self.browse(cr, uid, ids, context=context):
            dicto = {
                'name': "Cancelled and Re-Assessment",
                'who': uid,
                'when': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            }
            follow_list.append((0, 0, dicto))
            output = rec.wakf_id.id or False
            acc_year = rec.account_year.id or False
            ass_year = rec.assessment_year.id or False
            self.write(cr, uid, ids, {
                'state': 're_assessment',
                'follow_line_id': follow_list
            })
            search_invoice = self.pool.get('account.invoice').search(
                cr, uid, [('partner_id', '=', output),
                          ('assess_year_saleorder', '=', acc_year),
                          ('account_year_saleorder', '=', ass_year),
                          ('is_assessment', '=', True),
                          ('appli_no', '=', False),
                          ('assessment_type', '=', 'bj'),
                          ('state', '=', 'draft')])
            list_unlink = [
                invoice.id
                for invoice in self.pool.get('account.invoice').browse(
                    cr, uid, search_invoice)
            ]
            self.pool.get('account.invoice').unlink(cr,
                                                    uid,
                                                    list_unlink,
                                                    context=context)
        return True

    def action_rr(self, cr, uid, ids, context=None):
        follow_list = []
        dicto = {}
        for rec in self.browse(cr, uid, ids, context=context):
            dicto = {
                'name': "Send RR",
                'who': uid,
                'when': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
            }
            follow_list.append((0, 0, dicto))
            reg_no = rec.reg_no
            output = rec.wakf_id.id or False
            acc_year = rec.account_year.id or False
            ass_year = rec.assessment_year.id or False
            search_invoice = self.pool.get('account.invoice').search(
                cr, uid, [('partner_id', '=', output),
                          ('assess_year_saleorder', '=', acc_year),
                          ('account_year_saleorder', '=', ass_year),
                          ('is_assessment', '=', True),
                          ('appli_no', '=', False),
                          ('assessment_type', '=', 'bj'),
                          ('state', '=', 'draft')])
            if search_invoice:
                list_unlink = [
                    invoice.id
                    for invoice in self.pool.get('account.invoice').browse(
                        cr, uid, search_invoice)
                ]
                self.pool.get('account.invoice').unlink(cr,
                                                        uid,
                                                        list_unlink,
                                                        context=context)
                self.write(cr, uid, ids, {
                    'state': 'rr',
                    'follow_line_id': follow_list
                })
                ##########################################  RR Created  ##########################################
                id_create = self.pool.get('revenue.recovery').create(
                    cr, uid, {
                        'from_a': 'bj',
                        'reg_no': reg_no,
                        'partner_id': output,
                        'assess_year': ass_year,
                        'account_year': acc_year
                    })
                return {
                    'type': 'ir.actions.act_window',
                    'name': "Revenue Recovery form",
                    'view_type': 'form',
                    'view_mode': 'form',
                    'context': context,
                    'res_id': id_create,
                    #'domain' : [('order_id','in',sale_ids)],
                    'res_model': 'revenue.recovery',
                    'target': 'new',
                    'nodestroy': True,
                }
            else:
                raise osv.except_osv(
                    _('Cannot Process!'),
                    _('BJ Invoice moved to "post" or "paid" state. First Cancel Invoice'
                      ))
        return True

    def showcause(self, cr, uid, ids, context=None):
        acc_year_1 = False
        acc_year = False
        for key in self.browse(cr, uid, ids, context=context):
            reg_no = key.reg_no
            output = key.wakf_id.id
            amount = key.contri_amount
            assessment_year = key.assessment_year.id
            count = 0
            for bj_line in key.bj_line_id:
                if count == 0:
                    acc_year_1 = bj_line.account_year_line.id
                acc_year = bj_line.account_year_line.id
                count += 1
            self.pool.get('show.cause').create(
                cr, uid, {
                    'reg_no': reg_no,
                    'assessment_year': assessment_year,
                    'acc_year_from': acc_year_1,
                    'partner_id': output,
                    'acc_year_to': acc_year,
                    'amount': amount
                })
            self.write(cr, uid, ids, {'state': 'showcause'})
        return False

    _columns = {
        'reg_no':
        fields.integer('Registration No:', size=16),
        'wakf_id':
        fields.many2one('res.partner', 'Wakf Name'),
        'ass_date':
        fields.date('Assessment Date', size=16),
        'net_assess':
        fields.float('Net Income(Assessment)'),
        'net_bj':
        fields.float('Net Income(BJ)'),
        'contribution':
        fields.float('Contribution'),
        'assessment_year':
        fields.many2one('account.fiscalyear',
                        'Assessment Year',
                        ondelete='set null'),
        'account_year':
        fields.many2one('account.fiscalyear',
                        'Account Year',
                        ondelete='set null'),
        'follow_line_id':
        fields.one2many('follow.up.bj', 'follow_id', 'FOLLOW UPs'),
        'state':
        fields.selection(
            (('draft', 'Draft'), ('approved', 'BJ Confirmed'),
             ('send', 'BJ Send'), ('re_assessment', 'Re-Assessment'),
             ('rr', 'RR Send'), ('cancelled', 'BJ Cancelled'),
             ('completed', 'BJ Completed')),
            'BJ State',
            required=False),
        'user_id':
        fields.char('user id', size=16),
        'company_id':
        fields.many2one('res.company', 'Company', required=False)
    }
    _defaults = {
        'assessment_year':
        _deflt_ass_year,
        'state':
        'approved',
        'user_id':
        lambda obj, cr, uid, context: uid,
        'company_id':
        lambda self, cr, uid, ctx: self.pool['res.company'].
        _company_default_get(
            cr, uid, object='bj.assessment.window', context=ctx)
    }
Пример #41
0
     
 _inherit = "res.company"
 _columns = {
     ### activate the currency update
     'auto_currency_up': fields.boolean('Automatical update of the currency this company'),
     'services_to_use' : fields.one2many(
                                         'currency.rate.update.service', 
                                         'company_id',
                                         'Currency update services' 
                                         ),
     ###predifine cron frequence
     'interval_type': fields.selection(
                                             [
                                                 ('days','Day(s)'), 
                                                 ('weeks', 'Week(s)'), 
                                                 ('months', 'Month(s)')
                                             ],
                                             'Currency update frequence',
                                             help="""changing this value will
                                              also affect other compagnies"""
                                         ),
     ###function field that allows to know the
     ###mutli company currency implementation
     'multi_company_currency_enable' : fields.function(
                                         _multi_curr_enable,
                                         method=True,
                                         type='boolean',
                                         string="Multi company currency",
                                         help='if this case is not check you can'+\
                                         ' not set currency is active on two company'
                                     ),
 }
Пример #42
0
class crm_claim_report(osv.osv):
    """ CRM Claim Report"""

    _name = "crm.claim.report"
    _auto = False
    _description = "CRM Claim Report"

    _columns = {
        'name': fields.char('Year', size=64, required=False, readonly=True),
        'user_id':fields.many2one('res.users', 'User', readonly=True),
        'section_id':fields.many2one('crm.case.section', 'Section', readonly=True),
        'nbr': fields.integer('# of Cases', readonly=True),
        'state': fields.selection(AVAILABLE_STATES, 'Status', size=16, readonly=True),
        'month':fields.selection([('01', 'January'), ('02', 'February'), \
                                  ('03', 'March'), ('04', 'April'),\
                                  ('05', 'May'), ('06', 'June'), \
                                  ('07', 'July'), ('08', 'August'),\
                                  ('09', 'September'), ('10', 'October'),\
                                  ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', readonly=True),
        'create_date': fields.datetime('Create Date', readonly=True, select=True),
        'day': fields.char('Day', size=128, readonly=True),
        'delay_close': fields.float('Delay to close', digits=(16,2),readonly=True, group_operator="avg",help="Number of Days to close the case"),
        'stage_id': fields.many2one ('crm.case.stage', 'Stage', readonly=True,domain="[('section_ids','=',section_id)]"),
        'categ_id': fields.many2one('crm.case.categ', 'Category',\
                         domain="[('section_id','=',section_id),\
                        ('object_id.model', '=', 'crm.claim')]", readonly=True),
        'partner_id': fields.many2one('res.partner', 'Partner', readonly=True),
        'company_id': fields.many2one('res.company', 'Company', readonly=True),
        'priority': fields.selection(AVAILABLE_PRIORITIES, 'Priority'),
        'type_action': fields.selection([('correction','Corrective Action'),('prevention','Preventive Action')], 'Action Type'),
        'date_closed': fields.date('Close Date', readonly=True, select=True),
        'date_deadline': fields.date('Deadline', readonly=True, select=True),
        'delay_expected': fields.float('Overpassed Deadline',digits=(16,2),readonly=True, group_operator="avg"),
        'email': fields.integer('# Emails', size=128, readonly=True)
    }

    def init(self, cr):

        """ Display Number of cases And Section Name
        @param cr: the current row, from the database cursor,
         """

        tools.drop_view_if_exists(cr, 'crm_claim_report')
        cr.execute("""
            create or replace view crm_claim_report as (
                select
                    min(c.id) as id,
                    to_char(c.date, 'YYYY') as name,
                    to_char(c.date, 'MM') as month,
                    to_char(c.date, 'YYYY-MM-DD') as day,
                    to_char(c.date_closed, 'YYYY-MM-DD') as date_closed,
                    to_char(c.date_deadline, 'YYYY-MM-DD') as date_deadline,
                    c.state,
                    c.user_id,
                    c.stage_id,
                    c.section_id,
                    c.partner_id,
                    c.company_id,
                    c.categ_id,
                    count(*) as nbr,
                    c.priority as priority,
                    c.type_action as type_action,
                    date_trunc('day',c.create_date) as create_date,
                    avg(extract('epoch' from (c.date_closed-c.create_date)))/(3600*24) as  delay_close,
                    (SELECT count(id) FROM mail_message WHERE model='crm.claim' AND res_id=c.id) AS email,
                    extract('epoch' from (c.date_deadline - c.date_closed))/(3600*24) as  delay_expected
                from
                    crm_claim c
                group by to_char(c.date, 'YYYY'), to_char(c.date, 'MM'),to_char(c.date, 'YYYY-MM-DD'),\
                        c.state, c.user_id,c.section_id, c.stage_id,\
                        c.categ_id,c.partner_id,c.company_id,c.create_date,
                        c.priority,c.type_action,c.date_deadline,c.date_closed,c.id
            )""")
#You should have received a copy of the GNU Affero General Public License       #
#along with this program.  If not, see <http://www.gnu.org/licenses/>.          #
#################################################################################

import time

from osv import osv, fields
import decimal_precision as dp

FISCAL_RULE_COLUMNS = {
                       'partner_fiscal_type_id': fields.many2one('l10n_br_account.partner.fiscal.type', 
                                                                 'Tipo Fiscal do Parceiro'),
                       'fiscal_operation_category_id': fields.many2one('l10n_br_account.fiscal.operation.category', 
                                                                       'Categoria', requeried=True),
                       'fiscal_type': fields.selection([('1', 'Simples Nacional'), 
                                                        ('2', 'Simples Nacional – excesso de sublimite de receita bruta'), 
                                                        ('3', 'Regime Normal')], 
                                                       'Regime Tributário', required=True),
                       'revenue_start': fields.float('Faturamento Inicial',
                                                     digits_compute=dp.get_precision('Account'),
                                                     help="Faixa inicial de faturamento bruto"),
                       'revenue_end': fields.float('Faturamento Final',
                                                   digits_compute=dp.get_precision('Account'),
                                                   help="Faixa inicial de faturamento bruto"),}

FISCAL_RULE_DEFAULTS = {
                        'fiscal_type': '3',
                        'revenue_start': 0.00,
                        'revenue_end': 0.00,}

class account_fiscal_position_rule_template(osv.osv):
    _inherit = 'account.fiscal.position.rule.template'
Пример #44
0
class subscription_subscription(osv.osv):
    _name = "subscription.subscription"
    _description = "Subscription"
    _columns = {
        'name':
        fields.char('Name', size=60, required=True),
        'active':
        fields.boolean(
            'Active',
            help=
            "If the active field is set to False, it will allow you to hide the subscription without removing it."
        ),
        'partner_id':
        fields.many2one('res.partner', 'Partner'),
        'notes':
        fields.text('Notes'),
        'user_id':
        fields.many2one('res.users', 'User', required=True),
        'interval_number':
        fields.integer('Interval Qty'),
        'interval_type':
        fields.selection([('days', 'Days'), ('weeks', 'Weeks'),
                          ('months', 'Months')], 'Interval Unit'),
        'exec_init':
        fields.integer('Number of documents'),
        'date_init':
        fields.datetime('First Date'),
        'state':
        fields.selection([('draft', 'Draft'), ('running', 'Running'),
                          ('done', 'Done')], 'State'),
        'doc_source':
        fields.reference(
            'Source Document',
            required=True,
            selection=_get_document_types,
            size=128,
            help=
            "User can choose the source document on which he wants to create documents"
        ),
        'doc_lines':
        fields.one2many('subscription.subscription.history',
                        'subscription_id',
                        'Documents created',
                        readonly=True),
        'cron_id':
        fields.many2one('ir.cron',
                        'Cron Job',
                        help="Scheduler which runs on subscription"),
        'note':
        fields.text('Notes', help="Description or Summary of Subscription"),
    }
    _defaults = {
        'date_init': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
        'user_id': lambda obj, cr, uid, context: uid,
        'active': lambda *a: True,
        'interval_number': lambda *a: 1,
        'interval_type': lambda *a: 'months',
        'doc_source': lambda *a: False,
        'state': lambda *a: 'draft'
    }

    def set_process(self, cr, uid, ids, context=None):
        for row in self.read(cr, uid, ids, context=context):
            mapping = {
                'name': 'name',
                'interval_number': 'interval_number',
                'interval_type': 'interval_type',
                'exec_init': 'numbercall',
                'date_init': 'nextcall'
            }
            res = {
                'model': 'subscription.subscription',
                'args': repr([[row['id']]]),
                'function': 'model_copy',
                'priority': 6,
                'user_id': row['user_id'] and row['user_id'][0]
            }
            for key, value in mapping.items():
                res[value] = row[key]
            id = self.pool.get('ir.cron').create(cr, uid, res)
            self.write(cr, uid, [row['id']], {
                'cron_id': id,
                'state': 'running'
            })
        return True

    def model_copy(self, cr, uid, ids, context=None):
        for row in self.read(cr, uid, ids, context=context):
            if not row.get('cron_id', False):
                continue
            cron_ids = [row['cron_id'][0]]
            remaining = self.pool.get('ir.cron').read(
                cr, uid, cron_ids, ['numbercall'])[0]['numbercall']
            try:
                (model_name, id) = row['doc_source'].split(',')
                id = int(id)
                model = self.pool.get(model_name)
            except:
                raise osv.except_osv(
                    _('Wrong Source Document !'),
                    _('Please provide another source document.\nThis one does not exist !'
                      ))

            default = {'state': 'draft'}
            doc_obj = self.pool.get('subscription.document')
            document_ids = doc_obj.search(cr, uid,
                                          [('model.model', '=', model_name)])
            doc = doc_obj.browse(cr, uid, document_ids)[0]
            for f in doc.field_ids:
                if f.value == 'date':
                    value = time.strftime('%Y-%m-%d')
                else:
                    value = False
                default[f.field.name] = value

            state = 'running'

            # if there was only one remaining document to generate
            # the subscription is over and we mark it as being done
            if remaining == 1:
                state = 'done'
            id = self.pool.get(model_name).copy(cr, uid, id, default, context)
            self.pool.get('subscription.subscription.history').create(
                cr, uid, {
                    'subscription_id': row['id'],
                    'date': time.strftime('%Y-%m-%d %H:%M:%S'),
                    'document_id': model_name + ',' + str(id)
                })
            self.write(cr, uid, [row['id']], {'state': state})
        return True

    def unlink(self, cr, uid, ids, context=None):
        for record in self.browse(cr, uid, ids, context or {}):
            if record.state == "running":
                raise osv.except_osv(
                    _('Error !'),
                    _('You cannot delete an active subscription !'))
        return super(subscription_subscription,
                     self).unlink(cr, uid, ids, context)

    def set_done(self, cr, uid, ids, context=None):
        res = self.read(cr, uid, ids, ['cron_id'])
        ids2 = [x['cron_id'][0] for x in res if x['id']]
        self.pool.get('ir.cron').write(cr, uid, ids2, {'active': False})
        self.write(cr, uid, ids, {'state': 'done'})
        return True

    def set_draft(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'draft'})
        return True
Пример #45
0
		return {'value': {
						'base_discount': valid_discount,
						'price_buffer':total_price,
# 		'balance':balance,
				}
			}

	def _estado_defecto(self, cr, uid, context=None):
		estado = self.pool.get('bag.state').search(cr, uid, [('name', '=', 'Recibido')])
		return estado

	_name = 'bag.service'
	_description = 'Service Order'
	_columns = {
		'name': fields.char('Numero Orden', size=24),
		'type': fields.selection([('particular', 'Particular'), ('airline', 'Aerolinea')], 'Type', required=True),
		'date': fields.date('Fecha', required=True),
		'date_promised': fields.date('Fecha Prometida', required=True),
		'partner_id' : fields.many2one('res.partner', 'Cliente'),
		'address_str': fields.related('partner_id', 'street', type='char', size='128'),
		'address_num_str': fields.related('partner_id', 'street_num', type='char'),
		'piso_dpto_str': fields.related('partner_id', 'piso_dpto', type='char', size='128'),
		'phone_str': fields.related('partner_id', 'phone_str', type='char', size='128'),
		'zone_str': fields.related('partner_id', 'street', type='char'),
		'type_id': fields.many2one('bag.type', 'Tipo'),
		'format_id': fields.many2one('bag.format', 'Formato'),
		'color_id': fields.many2one('bag.color', 'Color'),
		'material_id': fields.many2one('bag.material', 'Material'),
		'size_id': fields.many2one('bag.size', 'Tamano'),
		'description': fields.char('Descripcion', size=64),
		'brand': fields.char('Marca', size=64),
Пример #46
0
class res_company(osv.osv):
    _name = "res.company"
    _description = 'Companies'
    _order = 'name'

    def _get_address_data(self, cr, uid, ids, field_names, arg, context=None):
        """ Read the 'address' functional fields. """
        result = {}
        part_obj = self.pool.get('res.partner')
        address_obj = self.pool.get('res.partner.address')
        for company in self.browse(cr, uid, ids, context=context):
            result[company.id] = {}.fromkeys(field_names, False)
            if company.partner_id:
                address_data = part_obj.address_get(cr,
                                                    uid,
                                                    [company.partner_id.id],
                                                    adr_pref=['default'])
                if address_data['default']:
                    address = address_obj.read(cr,
                                               uid,
                                               address_data['default'],
                                               field_names,
                                               context=context)
                    for field in field_names:
                        result[company.id][field] = address[field] or False
        return result

    def _get_bank_data(self, cr, uid, ids, field_names, arg, context=None):
        """ Read the 'address' functional fields. """
        result = {}
        for company in self.browse(cr, uid, ids, context=context):
            r = []
            for bank in company.bank_ids:
                if bank.footer:
                    r.append(bank.name_get(context=context)[0][1])
            result[company.id] = ' | '.join(r)
        return result

    def _set_address_data(self,
                          cr,
                          uid,
                          company_id,
                          name,
                          value,
                          arg,
                          context=None):
        """ Write the 'address' functional fields. """
        company = self.browse(cr, uid, company_id, context=context)
        if company.partner_id:
            part_obj = self.pool.get('res.partner')
            address_obj = self.pool.get('res.partner.address')
            address_data = part_obj.address_get(cr,
                                                uid, [company.partner_id.id],
                                                adr_pref=['default'])
            address = address_data['default']
            if address:
                address_obj.write(cr, uid, [address], {name: value or False})
            else:
                address_obj.create(cr,
                                   uid, {
                                       name: value or False,
                                       'partner_id': company.partner_id.id
                                   },
                                   context=context)
        return True

    def _get_thumbed_image(self, cr, uid, ids, name, args, context=None):
        """Insert thumbed company logo into new logo_web field every time is it overwritten or at the first time it is created"""
        if not ids:
            return {}
        result = {}
        for company_obj in self.browse(cr, uid, ids):
            if company_obj.logo:
                result[company_obj.id] = self.compress_image(company_obj.logo)
        return result

    _columns = {
        'name':
        fields.related('partner_id',
                       'name',
                       string='Company Name',
                       size=128,
                       required=True,
                       store=True,
                       type='char'),
        'parent_id':
        fields.many2one('res.company', 'Parent Company', select=True),
        'child_ids':
        fields.one2many('res.company', 'parent_id', 'Child Companies'),
        'partner_id':
        fields.many2one('res.partner', 'Partner', required=True),
        'rml_header1':
        fields.char(
            'Report Header / Company Slogan',
            size=200,
            help=
            "Appears by default on the top right corner of your printed documents."
        ),
        'rml_footer1':
        fields.char('General Information Footer', size=200),
        'rml_footer2':
        fields.function(
            _get_bank_data,
            type="char",
            string='Bank Accounts Footer',
            size=250,
            store=True,
            help=
            "This field is computed automatically based on bank accounts defined, having the display on footer checkbox set."
        ),
        'rml_header':
        fields.text('RML Header', required=True),
        'rml_header2':
        fields.text('RML Internal Header', required=True),
        'rml_header3':
        fields.text('RML Internal Header', required=True),
        'logo':
        fields.binary('Logo'),
        'logo_web':
        fields.function(_get_thumbed_image,
                        method=True,
                        string='Web_logo',
                        type='binary',
                        store=True),
        'currency_id':
        fields.many2one('res.currency', 'Currency', required=True),
        'currency_ids':
        fields.one2many('res.currency', 'company_id', 'Currency'),
        'user_ids':
        fields.many2many('res.users', 'res_company_users_rel', 'cid',
                         'user_id', 'Accepted Users'),
        'account_no':
        fields.char('Account No.', size=64),
        'street':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=128,
                        type='char',
                        string="Street",
                        multi='address'),
        'street2':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=128,
                        type='char',
                        string="Street2",
                        multi='address'),
        'zip':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=24,
                        type='char',
                        string="Zip",
                        multi='address'),
        'city':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=24,
                        type='char',
                        string="City",
                        multi='address'),
        'state_id':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        type='many2one',
                        domain="[('country_id', '=', country_id)]",
                        relation='res.country.state',
                        string="Fed. State",
                        multi='address'),
        'bank_ids':
        fields.one2many('res.partner.bank',
                        'company_id',
                        'Bank Accounts',
                        help='Bank accounts related to this company'),
        'country_id':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        type='many2one',
                        relation='res.country',
                        string="Country",
                        multi='address'),
        'email':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=64,
                        type='char',
                        string="Email",
                        multi='address'),
        'phone':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=64,
                        type='char',
                        string="Phone",
                        multi='address'),
        'fax':
        fields.function(_get_address_data,
                        fnct_inv=_set_address_data,
                        size=64,
                        type='char',
                        string="Fax",
                        multi='address'),
        'website':
        fields.related('partner_id',
                       'website',
                       string="Website",
                       type="char",
                       size=64),
        'vat':
        fields.related('partner_id',
                       'vat',
                       string="Tax ID",
                       type="char",
                       size=32),
        'company_registry':
        fields.char('Company Registry', size=64),
        'paper_format':
        fields.selection([('a4', 'A4'), ('us_letter', 'US Letter')],
                         "Paper Format",
                         required=True),
    }
    _sql_constraints = [('name_uniq', 'unique (name)',
                         'The company name must be unique !')]

    def on_change_header(self,
                         cr,
                         uid,
                         ids,
                         phone,
                         email,
                         fax,
                         website,
                         vat,
                         reg=False,
                         context=None):
        val = []
        if phone: val.append(_('Phone: ') + phone)
        if fax: val.append(_('Fax: ') + fax)
        if website: val.append(_('Website: ') + website)
        if vat: val.append(_('VAT: ') + vat)
        if reg: val.append(_('Reg: ') + reg)
        return {'value': {'rml_footer1': ' | '.join(val)}}

    def _search(self,
                cr,
                uid,
                args,
                offset=0,
                limit=None,
                order=None,
                context=None,
                count=False,
                access_rights_uid=None):

        if context is None:
            context = {}
        user_preference = context.get('user_preference', False)
        if user_preference:
            # We browse as superuser. Otherwise, the user would be able to
            # select only the currently visible companies (according to rules,
            # which are probably to allow to see the child companies) even if
            # she belongs to some other companies.
            user = self.pool.get('res.users').browse(cr,
                                                     1,
                                                     uid,
                                                     context=context)
            cmp_ids = list(
                set([user.company_id.id] +
                    [cmp.id for cmp in user.company_ids]))
            return cmp_ids
        return super(res_company,
                     self)._search(cr,
                                   uid,
                                   args,
                                   offset=offset,
                                   limit=limit,
                                   order=order,
                                   context=context,
                                   count=count,
                                   access_rights_uid=access_rights_uid)

    def _company_default_get(self,
                             cr,
                             uid,
                             object=False,
                             field=False,
                             context=None):
        """
        Check if the object for this company have a default value
        """
        if not context:
            context = {}
        proxy = self.pool.get('multi_company.default')
        args = [
            ('object_id.model', '=', object),
            ('field_id', '=', field),
        ]

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

    @tools.ormcache()
    def _get_company_children(self, cr, uid=None, company=None):
        if not company:
            return []
        ids = self.search(cr, uid, [('parent_id', 'child_of', [company])])
        return ids

    def _get_partner_hierarchy(self, cr, uid, company_id, context=None):
        if company_id:
            parent_id = self.browse(cr, uid, company_id)['parent_id']
            if parent_id:
                return self._get_partner_hierarchy(cr, uid, parent_id.id,
                                                   context)
            else:
                return self._get_partner_descendance(cr, uid, company_id, [],
                                                     context)
        return []

    def _get_partner_descendance(self,
                                 cr,
                                 uid,
                                 company_id,
                                 descendance,
                                 context=None):
        descendance.append(self.browse(cr, uid, company_id).partner_id.id)
        for child_id in self._get_company_children(cr, uid, company_id):
            if child_id != company_id:
                descendance = self._get_partner_descendance(
                    cr, uid, child_id, descendance)
        return descendance

    #
    # This function restart the cache on the _get_company_children method
    #
    def cache_restart(self, cr):
        self._get_company_children.clear_cache(self)

    def compress_image(self, img_str):
        logo = cStringIO.StringIO()
        small_logo = Image.open(
            cStringIO.StringIO(base64.decodestring(img_str)))
        small_logo.thumbnail((300, 300), Image.ANTIALIAS)
        small_logo.save(logo, format='PNG')
        small_logo = base64.encodestring(logo.getvalue())
        return small_logo

    def create(self, cr, uid, vals, context=None):
        if not vals.get('name', False) or vals.get('partner_id', False):
            self.cache_restart(cr)
            return super(res_company, self).create(cr,
                                                   uid,
                                                   vals,
                                                   context=context)
        obj_partner = self.pool.get('res.partner')
        partner_id = obj_partner.create(cr,
                                        uid, {'name': vals['name']},
                                        context=context)
        vals.update({'partner_id': partner_id})
        if 'logo' in vals and vals.get('logo') is not False:
            vals['logo_web'] = self.compress_image(vals.get('logo'))
        self.cache_restart(cr)
        company_id = super(res_company, self).create(cr,
                                                     uid,
                                                     vals,
                                                     context=context)
        obj_partner.write(cr,
                          uid,
                          partner_id, {'company_id': company_id},
                          context=context)
        return company_id

    def write(self, cr, uid, ids, vals, context={}):
        self.cache_restart(cr)
        if 'logo' in vals:
            if vals['logo']:
                vals['logo_web'] = self.compress_image(vals['logo'])
            else:
                vals['logo_web'] = vals['logo'] or vals.get('logo_web')
        return super(res_company, self).write(cr,
                                              uid,
                                              ids,
                                              vals,
                                              context=context)

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

    def _get_logo(self, cr, uid, ids):
        return open(
            os.path.join(tools.config['root_path'], 'addons', 'base', 'res',
                         'res_company_logo.png'), 'rb').read().encode('base64')

    _header = """
<header>
<pageTemplate>
    <frame id="first" x1="28.0" y1="28.0" width="%s" height="%s"/>
    <pageGraphics>
        <fill color="black"/>
        <stroke color="black"/>
        <setFont name="DejaVu Sans" size="8"/>
        <drawString x="%s" y="%s"> [[ formatLang(time.strftime("%%Y-%%m-%%d"), date=True) ]]  [[ time.strftime("%%H:%%M") ]]</drawString>
        <setFont name="DejaVu Sans Bold" size="10"/>
        <drawCentredString x="%s" y="%s">[[ company.partner_id.name ]]</drawCentredString>
        <stroke color="#000000"/>
        <lines>%s</lines>
    </pageGraphics>
</pageTemplate>
</header>"""

    _header2 = _header % (539, 772, "1.0cm", "28.3cm", "11.1cm", "28.3cm",
                          "1.0cm 28.1cm 20.1cm 28.1cm")

    _header3 = _header % (786, 525, 25, 555, 440, 555, "25 550 818 550")

    def _get_header(self, cr, uid, ids):
        try:
            header_file = tools.file_open(
                os.path.join('base', 'report', 'corporate_rml_header.rml'))
            try:
                return header_file.read()
            finally:
                header_file.close()
        except:
            return self._header_a4

    _header_main = """
    <header>
    <pageTemplate>
        <frame id="first" x1="1.3cm" y1="2.5cm" height="%s" width="19.0cm"/>
        <pageGraphics>
            <!-- You Logo - Change X,Y,Width and Height -->
            <image x="1.3cm" y="%s" height="40.0" >[[ company.logo or removeParentNode('image') ]]</image>
            <setFont name="DejaVu Sans" size="8"/>
            <fill color="black"/>
            <stroke color="black"/>
            <lines>1.3cm %s 20cm %s</lines>

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


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

            <!--page bottom-->

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

            <drawCentredString x="10.5cm" y="1.7cm">[[ company.rml_footer1 ]]</drawCentredString>
            <drawCentredString x="10.5cm" y="1.25cm">[[ company.rml_footer2 ]]</drawCentredString>
            <drawCentredString x="10.5cm" y="0.8cm">Contact : [[ user.name ]] - Page: <pageNumber/></drawCentredString>
        </pageGraphics>
    </pageTemplate>
</header>"""

    _header_a4 = _header_main % (
        '23.0cm', '27.6cm', '27.7cm', '27.7cm', '27.8cm', '27.2cm', '26.8cm',
        '26.4cm', '26.0cm', '26.0cm', '25.6cm', '25.6cm', '25.5cm', '25.5cm')
    _header_letter = _header_main % (
        '21.3cm', '25.9cm', '26.0cm', '26.0cm', '26.1cm', '25.5cm', '25.1cm',
        '24.7cm', '24.3cm', '24.3cm', '23.9cm', '23.9cm', '23.8cm', '23.8cm')

    def onchange_paper_format(self, cr, uid, ids, paper_format, context=None):
        if paper_format == 'us_letter':
            return {'value': {'rml_header': self._header_letter}}
        return {'value': {'rml_header': self._header_a4}}

    _defaults = {
        'currency_id': _get_euro,
        'paper_format': 'a4',
        'rml_header': _get_header,
        'rml_header2': _header2,
        'rml_header3': _header3,
        'logo': _get_logo
    }

    _constraints = [
        (osv.osv._check_recursion,
         'Error! You can not create recursive companies.', ['parent_id'])
    ]
Пример #47
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)),
Пример #48
0
class partner_update_wizard(osv.TransientModel):
    _name = 'partner.update.wizard'
    _columns = {
        'state': fields.selection([('step1', 'step1'), ('step2', 'step2')]),
        'log': fields.text('Log')
    }

    _defaults = {'state': 'step1'}

    # It looks for partners to update and update them.
    # It returns a log file with evidence of operations done.
    def partner_update(self, cr, uid, ids, context=None):
        #        pdb.set_trace()
        log = ''
        user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid)
        italy = pooler.get_pool(cr.dbname).get('res.country').search(
            cr, uid, [('code', '=', 'IT')])
        partners = pooler.get_pool(cr.dbname).get('res.partner').search(
            cr, uid, [('province', '!=', None), ('state_id', '=', None), '|',
                      ('company_id.id', '=', user.company_id.id),
                      ('company_id.id', 'child_of', user.company_id.id)])
        n_partners = len(partners)
        if n_partners > 0:
            p = pooler.get_pool(cr.dbname).get('res.partner')
            for i in range(n_partners):
                partner_obj = pooler.get_pool(
                    cr.dbname).get('res.partner').browse(cr, uid, partners[i])
                if partner_obj:
                    if partner_obj.country_id:
                        country_to_find = partner_obj.country_id.id
                        update_country = False
                    else:
                        country_to_find = italy[0]
                        update_country = True

                    state_id = self.pool.get('res.country.state').search(
                        cr, uid, [('code', '=', partner_obj.province.code),
                                  ('country_id', '=', country_to_find)])
                    if state_id:
                        state_obj = pooler.get_pool(
                            cr.dbname).get('res.country.state').browse(
                                cr, uid, state_id[0])
                        if state_obj:
                            if update_country:
                                vals = {
                                    'state_id': state_obj.id,
                                    'country_id': country_to_find
                                }
                            else:
                                vals = {'state_id': state_obj.id}
                            id_upd = [partner_obj.id]
                            p.write(cr, uid, id_upd, vals, context=context)
                            log += _('Updated: ') + partner_obj.name
                            log += ' ' + partner_obj.zip + ' '
                            log += partner_obj.city + ' '
                            log += state_obj.code + ' \n'

            log += _('Updated Partners: ') + str(n_partners)

            cpy = pooler.get_pool(cr.dbname).\
                get('res.company').search(cr,
                                          uid,
                                          ['|',
                                           ('id', '=',
                                            user.company_id.id),
                                           ('id', 'child_of',
                                            user.company_id.id)])
            c = pooler.get_pool(cr.dbname).get('res.company')
            for i in range(len(cpy)):
                c.write(cr,
                        uid,
                        cpy[i], {'it_partner_updated': True},
                        context=context)

        else:
            log += _('No Partner needs to be updated.')

        self.write(cr,
                   uid,
                   ids, {
                       'state': 'step2',
                       'log': log
                   },
                   context=context)
        wiz = self.browse(cr, uid, ids, context=context)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'partner.update.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': wiz[0].id,
            'views': [(False, 'form')],
            'target': 'new',
            'context': context,
        }
Пример #49
0
        res = obj.read(cr, uid, ids, ["code", "name"], context)
        return [(r["code"], r["name"]) for r in res]

    def _get_xml_id(self, cr, uid, ids, *args, **kwargs):
        model_data_obj = self.pool.get("ir.model.data")
        data_ids = model_data_obj.search(cr, uid, [("model", "=", self._name), ("res_id", "in", ids)])
        data_results = model_data_obj.read(cr, uid, data_ids, ["module", "name", "res_id"])
        result = {}
        for id in ids:
            result[id] = False
        for record in data_results:
            result[record["res_id"]] = "%(module)s.%(name)s" % record
        return result

    _columns = {
        "charset": fields.selection(_get_encodings, string="Charset", required=True),
        "content_fname": fields.char("Override Extension", size=64, help="Here you can override output file extension"),
        "styles_mode": fields.selection(
            [("default", "Not used"), ("global", "Global"), ("specified", "Specified")], string="Stylesheet"
        ),
        #'report_styles' : fields.binary('Template Styles', help='OpenOffice stylesheet (.odt)'),
        "stylesheet_id": fields.many2one("report.stylesheets", "Template Stylesheet"),
        "preload_mode": fields.selection([("static", _("Static")), ("preload", _("Preload"))], "Preload Mode"),
        "tml_source": fields.selection(
            [("database", "Database"), ("file", "File"), ("parser", "Parser")], "Template source", select=True
        ),
        "parser_def": fields.text("Parser Definition"),
        "parser_loc": fields.char(
            "Parser location",
            size=128,
            help="Path to the parser location. Beginning of the path must be start with the module name!\nLike this: {module name}/{path to the parser.py file}",
Пример #50
0
class jmdavance(osv.Model):
    _name = "ea.avance"
    _inherit = "mail.thread"

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

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

    def action_rh(self, cr, uid, ids):
        for i in self.browse(cr, uid, ids):
            if i.gea_sea == "SEA":
                self.write(cr, uid, ids, {'state': 'edicion'})
            else:
                self.write(cr, uid, ids, {'state': 'rh'})
        return True

    def action_edicion(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'edicion'})
        for i in self.browse(cr, uid, ids, context):
            for j in i.cuota:
                #bono para el investigador
                monto = 0.0
                superv = 0.0
                if not j.cuestionario:
                    continue
                for k in j.cuestionario.salario_ids:
                    if (k.puesto == j.empleado.job_id and k.tipo == "propia"):
                        monto += k.monto
                    if (k.puesto == j.empleado.job_id and k.tipo == "equipo"):
                        superv += k.monto
                #if j.empleado and j.empleado.id:
                values = {
                    'name': ("Encuesta " + j.cuestionario.name),
                    'empleado': j.empleado.id,
                    'fecha': i.fecha,
                    'tipo': 'monto',
                    'state': 'aprobado',
                    'monto': monto * j.cantidad
                }
                self.pool.get("hr.bonos").create(cr, uid, values, context)
        return True

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

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

    def before2(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            if not i.h_envio:
                return
            a = i.h_envio
            b = a.find(":")
            c = b - 2
            a = a[c:b]
            ret[i.id] = False
            if a < 14:
                ret[i.id] = True
        return ret

    def get_name(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            ret[i.id] = str(i.proyecto.name) + " " +\
                str(i.plaza_id.codigo) + " " + str(i.fecha)
        return ret

    def generate_all(self, cr, uid, ids, context=None):
        for i in self.browse(cr, uid, self.search(cr, uid, [])):
            i.generate_payroll()

    def generate_payroll(self, cr, uid, ids, context=None):
        ret = {}
        nomina_obj = self.pool.get("avance.payroll")
        excepcion_obj = self.pool.get("hr.exception")
        for i in self.browse(cr, uid, ids, context):
            print("Ciclo del objeto")
            #Eliminando las anteriores
            for n in i.nominas:
                nomina_obj.unlink(cr, uid, [n.id])
            #Eliminando las excepciones
            for e in i.excepciones_ids:
                excepcion_obj.unlink(cr, uid, [e.id])
            calculados = []
            scalculados = []
            empleado_obj = self.pool.get("hr.employee")
            for j in i.cuota:
                print("Iterando en las cuotas")
                if j.stand_by or j.rechazada:
                    excepcion_obj.create(
                        cr, uid, {
                            'name': 'Entrevista cancelada o en pausa',
                            'description': ("Folio : " + str(j.folio)),
                            'avance_id': i.id,
                        })
                    continue
                if j.empleado.id not in calculados:
                    print(("El empleado no estaba en la lista " +
                           str(j.empleado.id)))
                    eid = j.empleado.id
                    calculados.append(eid)
                    #Verificando si el empleado esta validado para el proyecto
                    idproyecto = i.proyecto.id
                    validacion_obj = self.pool.get("empleado.validacion")
                    validado = False
                    for vd in validacion_obj.browse(
                            cr, uid,
                            validacion_obj.search(
                                cr, uid, [('name_related.id', '=', eid)])):
                        if vd.relation and vd.relation.name:
                            if idproyecto == vd.relation.name.id:
                                validado = True
                    if not validado:
                        excepcion_obj.create(
                            cr, uid, {
                                'name':
                                'Investigador no validado',
                                'description':
                                ("Empleado : " + str(j.empleado.name) +
                                 str(j.empleado.nombre)),
                                'avance_id':
                                i.id,
                            })
                        continue
                    total = 0
                    #obteniendo el puesto del empleado
                    jobid = 0
                    print("Justo antes del ciclo")
                    print((empleado_obj.search(cr, uid, [('id', '=', eid)])))
                    print("Despues de search")
                    for em in empleado_obj.browse(
                            cr, uid,
                            empleado_obj.search(cr, uid, [('id', '=', eid)])):
                        print(("Obteniendo el puesto" + str(em.job_id.name)))
                        if (em.job_id):
                            jobid = em.job_id.id
                    total = 0
                    conteo = 0
                    for k in i.cuota:
                        if k.empleado.id == eid:
                            print("El sueldo coincide")
                            #Leyendo los sueldos
                            for s in k.tiraje.cuestionario_id.salario_ids:
                                print("Buscando un salario que\
                                    coincida con el puesto")
                                print(("Probando puesto" + str(s.puesto.id) +
                                       "contra" + str(jobid)))
                                print(("Probando plaza" + str(s.plaza_id.id) +
                                       "contra" + str(i.plaza_id.id)))
                                print(("Probando concepto" + str(s.name.name) +
                                       "contra" + str(k.concepto.name)))
                                #s.puesto.id == jobid
                                if True and\
                                    s.plaza_id.id == i.plaza_id.id and\
                                    s.name.name == k.concepto.name:
                                    print("Sueldo encontrado")
                                    #Si es investigador
                                    print(("El tipo es " + str(s.tipo) + " " +
                                           str(s.tipo) == "propia"))
                                    if str(s.tipo) == "propia":
                                        print("Percepción propia")
                                        total = total + s.monto
                                        conteo += 1
                                        print("Sumando " + str(s.monto) +
                                              " a " + str(total))
                    #Escribiendo la nómina del empleado
                    print(
                        "La prouctividad es de -------------------------------- "
                        + str(total))
                    nomina_obj.create(
                        cr, uid, {
                            'empleado_id': j.empleado.id,
                            'productividad': total,
                            'relation': i.id,
                            'conteo': conteo,
                            'descripcion': i.proyecto.name + i.plaza_id.codigo
                        })
                    if total == 0.0:
                        excepcion_obj.create(
                            cr, uid, {
                                'name':
                                'Salario no encontrado',
                                'description':
                                ("Investigador : " + str(j.empleado.name) +
                                 str(j.empleado.nombre) +
                                 " Revisar puesto, plaza\
                            y criterio de pago"),
                                'avance_id':
                                i.id,
                            })
            print("====SUPERVISOR=====")
            for j in i.cuota:
                print("Iterando en las cuotas Supervisor")
                if j.stand_by or j.rechazada:
                    continue
                if j.supervisor.id not in scalculados:
                    print(("El supervisor no estaba en la lista " +
                           str(j.supervisor.id)))
                    eid = j.supervisor.id
                    scalculados.append(eid)
                    #Verificando si el empleado esta validado para el proyecto
                    idproyecto = i.proyecto.id
                    validacion_obj = self.pool.get("empleado.validacion")
                    validado = False
                    for vd in validacion_obj.browse(
                            cr, uid,
                            validacion_obj.search(
                                cr, uid, [('name_related.id', '=', eid)])):
                        if vd.relation and vd.relation.name:
                            if idproyecto == vd.relation.name.id:
                                validado = True
                    if not validado:
                        excepcion_obj.create(
                            cr, uid, {
                                'name':
                                'Supervisor no validado',
                                'description':
                                ("Supervisor : " + str(j.supervisor.name) +
                                 str(j.supervisor.nombre)),
                                'avance_id':
                                i.id,
                            })
                        continue
                    total = 0
                    conteo = 0
                    #obteniendo el puesto del empleado
                    jobid = 0
                    print("Justo antes del ciclo")
                    print((empleado_obj.search(cr, uid, [('id', '=', eid)])))
                    print("Despues de search")
                    for em in empleado_obj.browse(
                            cr, uid,
                            empleado_obj.search(cr, uid, [('id', '=', eid)])):
                        print(("Obteniendo el puesto" + str(em.job_id.name)))
                        if (em.job_id):
                            jobid = em.job_id.id
                    total = 0
                    for k in i.cuota:
                        if k.supervisor.id == eid and k.tiraje.cuestionario_id.salario_ids:
                            print("El sueldo coincide")
                            #Leyendo los sueldos
                            for s in k.tiraje.cuestionario_id.salario_ids:
                                print("Buscando un salario que\
                                    coincida con el puesto")
                                print(("Probando puesto" + str(s.puesto.id) +
                                       "contra" + str(jobid)))
                                print(("Probando plaza" + str(s.plaza_id.id) +
                                       "contra" + str(i.plaza_id.id)))
                                print(("Probando concepto" + str(s.name.name) +
                                       "contra" + str(k.concepto.name)))
                                #s.puesto.id == jobid
                                if True and\
                                    s.plaza_id.id == i.plaza_id.id and\
                                    s.name.name == k.concepto.name:
                                    print("Sueldo encontrado")
                                    #Si es investigador
                                    print(("El tipo es " + str(s.tipo) + " " +
                                           str(s.tipo) == "equipo"))
                                    if str(s.tipo) == "equipo":
                                        print("Percepción de equipo")
                                        total = total + s.monto
                                        conteo += 1
                                        print("Sumando " + str(s.monto) +
                                              " a " + str(total))
                    #Escribiendo la nómina del empleado
                    nomina_obj.create(
                        cr, uid, {
                            'empleado_id': j.supervisor.id,
                            'productividad': total,
                            'conteo': conteo,
                            'relation': i.id,
                            'descripcion': i.proyecto.name + i.plaza_id.codigo
                        })
                    if total == 0.0:
                        excepcion_obj.create(
                            cr, uid, {
                                'name':
                                'Salario no encontrado',
                                'description':
                                ("Empleado : " + str(j.supervisor.name) +
                                 str(j.supervisor.nombre) + " Revisar puesto,\
                            plaza y criterio de pago"),
                                'avance_id':
                                i.id,
                            })
        return ret

    def calculate_all(self, cr, uid, ids, context=None):
        for i in self.browse(cr, uid, self.search(cr, uid, [])):
            i.calculate()

    def calculate(self, cr, uid, ids, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            for j in i.nominas:
                total = 0.0
                for cp in j.conceptos_pago:
                    for lp in cp.linea_ids:
                        if str(lp.tipo) == "monto":
                            total = total + lp.monto
                        elif str(lp.tipo) == "dias":
                            total = total + (float(j.salario) * lp.dias)
                total = total + j.productividad
                self.pool.get("avance.payroll").write(cr, uid, [j.id],
                                                      {'monto': total})
        return ret

    def enviar_all(self, cr, uid, ids, conext=None):
        for i in self.browse(cr, uid, self.search(cr, uid, [])):
            i.enviar_rrhh()

    def enviar_rrhh(self, cr, uid, ids, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            if i.enviada:
                pass
                #return
            for j in i.nominas:
                bono_obj = self.pool.get("hr.bonos")
                print("Enviando el bono ")
                #print("Fecha " + str(i.fecha))
                print("De la persona " + str(j.empleado_id.name))
                codigos_str = ""
                for k in j.conceptos_pago:
                    codigos_str = codigos_str + k.name + ", "
                bono_obj.create(
                    cr, uid, {
                        'name': "Productividad " + i.tipo_reporte,
                        'cantidad': j.conteo,
                        'empleado': j.empleado_id.id,
                        'monto': j.monto,
                        'tipo': 'monto',
                        'state': 'borrador',
                        'proyecto_id': i.proyecto.id,
                        'plaza': i.plaza_id.name,
                        'codigo_plaza': i.plaza_id.codigo,
                        'codigos_pago': codigos_str,
                        'fecha': i.fecha,
                        'hora_envio': i.h_envio,
                        'folio': i.folio,
                        'reporte_id': i.id,
                        'es_tableta': i.tablets,
                        'de_reporte': True,
                        'h_envio': time.strftime('%Y-%m-%d %H:%M:%S'),
                    })
                self.write(cr, uid, [i.id], {'enviada': True})
        return ret

    def extraarh_all(self, cr, uid, ids, context=None):
        for i in self.browse(cr, uid, self.search(cr, uid, [])):
            print("Haciendo " + str(i.id))
            i.extraarh()

    def extraarh(self, cr, uid, ids, context=None):
        ret = {}
        bono_obj = self.pool.get("hr.bonos")
        for i in self.browse(cr, uid, ids, context):
            for j in i.costo_ids:
                print("Checando a " + j.name + str(j.tipo_pago))
                #Revisamos si el empleado esta por productividad
                if j.tipo_pago == "productividad":
                    bono_obj.create(
                        cr, uid, {
                            'name': "Productividad " + i.tipo_reporte,
                            'cantidad': 0,
                            'empleado': j.id,
                            'monto': 0,
                            'tipo': 'dias',
                            'dias': 1,
                            'state': 'borrador',
                            'proyecto_id': i.proyecto.id,
                            'plaza': i.plaza_id.name,
                            'codigo_plaza': i.plaza_id.codigo,
                            'codigos_pago': "3,",
                            'fecha': i.fecha,
                            'hora_envio': i.h_envio,
                            'folio': i.folio,
                            'reporte_id': i.id,
                            'es_tableta': False,
                            'de_reporte': True,
                            'h_envio': time.strftime('%Y-%m-%d %H:%M:%S'),
                        })

    def unsend(self, cr, uid, ids, context=None):
        for i in self.browse(cr, uid, ids, context):
            print("Unsending")
            print(i.id)
            self.write(cr, uid, [i.id], {'enviada': False})

    def unsend_all(self, cr, uid, ids, context=None):
        for i in self.browse(cr, uid, self.search(cr, uid, [])):
            i.unsend()

    def do_reject(self, cr, uid, ids, context=None):
        avance_obj = self.pool.get("ea.avance.linea")
        rechazo_obj = self.pool.get("ea.rechazadas")
        aux_obj = self.pool.get('ea.reject')
        investigador = None
        for h in self.browse(cr, uid, ids, context):
            for i in h.aux_rechazar:
                if i.procesada:
                    continue
                cantidad_anterior = 0
                nueva_cantidad = 0
                for j in avance_obj.browse(cr, uid, [i.code], context):
                    cantidad_anterior = j.cantidad
                    nueva_cantidad = cantidad_anterior
                    investigador = j.empleado.id
                    supervisor = j.supervisor.id
                if i.cantidad <= cantidad_anterior:
                    nueva_cantidad = cantidad_anterior - i.cantidad
                avance_obj.write(cr, uid, [i.code], {
                    'cantidad': nueva_cantidad,
                    'procesada': True
                })
                rechazo_obj.create(
                    cr, uid, {
                        'investigador': investigador,
                        'revisor': i.persona.id,
                        'supervisor': supervisor,
                        'comentario': i.motivo,
                        'fase': i.avance_id.state,
                        'folio': j.folio,
                        'relation_avance': i.avance_id.id
                    })
            aux_obj.write(cr, uid, [i.id], {
                'procesada': "True",
                'usuario': uid
            })
        return {}

    def set_name(self, cr, uid, ids, fecha, context=None):
        ret = {}
        values = {}
        for i in self.browse(cr, uid, ids, context):
            values['name'] = str(i.proyecto.name) + " " +\
                str(i.plaza_id.codigo) + " " + str(fecha)
        ret['value'] = values
        return ret

    def add_lines(self, cr, uid, ids, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            avance_obj = self.pool.get("ea.avance.linea")
            print(range(5))
            print(range(i.aux_cantidad))
            for j in range(i.aux_cantidad):
                avance_obj.create(
                    cr, uid, {
                        'empleado': i.aux_levanto.id,
                        'supervisor': i.aux_supervisor.id,
                        'tiraje': i.aux_cuestionario.id,
                        'concepto': i.aux_criterio.id,
                        'relation_avance': i.id,
                    })
        return ret

    _columns = {
        'name':
        fields.function(get_name,
                        type="char",
                        string="Proyecto-Plaza-Fecha",
                        size=80),
        'proyecto':
        fields.many2one("project.project", string="Proyecto"),
        'nombre_corto':
        fields.related('proyecto',
                       'nombre_corto',
                       string="Nombre Corto",
                       type="char"),
        'plaza_id':
        fields.many2one("plaza", string="Plaza"),
        'fecha':
        fields.date(string="Fecha"),
        'cuota':
        fields.one2many("ea.avance.linea",
                        'relation_avance',
                        string="Linea de Avance",
                        ondelete="cascade"),
        'concepto_ids':
        fields.one2many("ea.avance.concepto",
                        "relation",
                        string="Conceptos de Pago"),
        'state':
        fields.selection([('capturado', 'Capturado'), ('enviado', 'Enviado'),
                          ('rh', 'Recursos Humanos'),
                          ('edicion', 'Supervisión de Oficina'),
                          ('pi', 'Procesos Intermedios'),
                          ('validado', 'Validado')], "Estado"),
        'incidencia_ids':
        fields.one2many("ea.incidencia", "relation", string="Incidencias"),
        'proyecto_id':
        fields.related("proyecto",
                       "id",
                       type="integer",
                       string="Id Proyecto",
                       store=True),
        'rechazadas_ids':
        fields.one2many("ea.rechazadas",
                        "relation_avance",
                        string="Encuestas Rechazadas"),
        'h_envio':
        fields.datetime("Hora de envío"),
        'b42':
        fields.function(before2, type="boolean", string="Antes de las 2"),
        'aux_rechazar':
        fields.one2many("ea.reject", "avance_id", string="Rechazo"),
        'nominas':
        fields.one2many("avance.payroll", 'relation', string="Nominas"),
        'calendarizacion':
        fields.binary("Calendarización"),
        'cal_name':
        fields.char("cal_name"),
        'observaciones':
        fields.text("Observaciones"),
        'supervisor':
        fields.many2one("hr.employee", string="Supervisor/Investigador"),
        'gea_sea':
        fields.selection([("gea", "GEA"), ("sea", "SEA")], string="GEA / SEA"),
        'partner_id':
        fields.many2one("res.partner", string="SEA"),
        'aux_levanto':
        fields.many2one("hr.employee", string="Levantó"),
        'aux_cantidad':
        fields.integer("Cantidad"),
        'aux_cuestionario':
        fields.many2one("ea.tiraje", string="Cuestionario"),
        'aux_supervisor':
        fields.many2one("hr.employee", string="Supervisor"),
        'aux_criterio':
        fields.many2one("ea.salario.concepto", string="Pago Entrevista"),
        'excepciones_ids':
        fields.one2many("hr.exception", "avance_id", string="Excepciones"),
        'codigo_sea':
        fields.many2one("res.partner", "Codigo del SEA"),
        'spot':
        fields.char("Spot"),
        'colonia':
        fields.char("Colonia/CLT"),
        'delegacion':
        fields.char("Delegación"),
        'calle1':
        fields.char("Calle 1"),
        'calle2':
        fields.char("Calle 2"),
        'cambio':
        fields.boolean("Cambio de Punto"),
        'inicio':
        fields.datetime("Inicio"),
        'colonia2':
        fields.char("Colonia/CLT"),
        'calle21':
        fields.char("Calle"),
        'calle22':
        fields.char("Calle"),
        'salida_oficina':
        fields.datetime("Hora de Salida de Oficina"),
        'llegada_campo':
        fields.datetime("Hora de Llegada a Campo"),
        "termino_campo":
        fields.datetime("Hora de Término de Campo"),
        "tienda":
        fields.char("Nombre de la Tienda"),
        "sucursal":
        fields.char("Sucursal"),
        "total":
        fields.float("Total de Registros"),
        "tipo":
        fields.selection([('entre', 'Entre Semana'), ('fin', 'Fin de Semana')],
                         string="Tipo"),
        "dia_semana":
        fields.selection([("Lunes", "Lunes"), ("Martes", "Martes"),
                          ("Miercoles", "Miercoles"), ("Jueves", "Jueves"),
                          ("Viernes", "Viernes"), ("Sabado", "Sabado"),
                          ("Domingo", "Domingo")],
                         string="Dia de la Semana"),
        "tipo_reporte":
        fields.selection([('entrevista', "Entrevista"),
                          ('registro', 'Registro')],
                         string="Tipo"),
        'enviada':
        fields.boolean("Enviada"),
        'tablets':
        fields.boolean("Tablets"),
        'folio':
        fields.char("Folio"),
        'costo_ids':
        fields.many2many("hr.employee", string="Cargar costos")
    }

    _defaults = {
        'h_envio': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
        'name': 'Proyecto-Plaza-Fecha',
        'folio':
        lambda self, cr, uid, context={}: self.pool.get('ir.sequence').get(
            cr, uid, 'ea.avance'),
    }
    _columns = {
        'name': fields.char(string='Name', select="1", size=150, 
            readonly=True),
        'service_type': fields.many2one('ups.codes', 'Service Type',
            domain=[('type', '=', 'service')], select="1"),
        'package_det': fields.one2many('ups.shippingregister.package',
            'shipping_register_rel', string='Packages',),
        'to_address': fields.many2one('res.partner.address',
            'Shipping Address', required=True),
        'from_address': fields.many2one('res.partner.address',
            'From Address', required=True),
        'shipper_address': fields.many2one('res.partner.address',
            'Shipper Address', required=True),
        'saturday_delivery': fields.boolean('Saturday Delivery?'),
        'description': fields.text('Description'),
        'state':fields.selection(STATE_SELECTION, 'Status', readonly=True,),

        # The following are UPS filled information
        'billed_weight':fields.float('Billed Weight', digits=(10, 4), 
            readonly=True, help=(
                'The billed weght may be different from the actual weight.'
                'This is computed by UPS.')),
        'billed_weight_uom':fields.many2one('product.uom', 'Billed Weight UOM',
            readonly=True),
        'total_amount':fields.float('Total Amount', digits=(14, 4),
            select="1", readonly=True),
        'total_amount_currency':fields.many2one('res.currency',
            'Total Amount Currency', select="2", readonly=True,),
        'digest': fields.binary('Information digest for DIGEST'),
        'notificationemailaddr': fields.char('Notification eMail Addresses',
            size=255, help='Separated by commas(,).'),
Пример #52
0
class jmdavancelinea(osv.Model):
    _name = "ea.avance.linea"

    # Employees can be searched by nombre or name
    def name_search(self,
                    cr,
                    uid,
                    name,
                    args=None,
                    operator='ilike',
                    context=None,
                    limit=100):
        if not args:
            args = []
        args = args[:]
        ids = []
        if name:
            ids = self.search(cr,
                              uid, [('folio', 'like', name)] + args,
                              limit=limit)
        return self.name_get(cr, uid, ids, context=context)

    #Display both names
    def name_get(self, cr, uid, ids, context=None):
        res = []
        reads = self.read(cr, uid, ids, ['folio'])
        res = []
        for record in reads:
            if record['folio']:
                name = record['folio']
            res.append((record['id'], name))
        return res

    def get_proyecto(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = "No Especificado"
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.proyecto.id
        return ret

    def get_plaza(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = 0
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.plaza_id.id
        return ret

    def get_plazaname(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = 0
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.plaza_id.name
        return ret

    def get_fecha(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = 0
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.fecha
        return ret

    def get_proyecton(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = "No Especificado"
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.proyecto.name
        return ret

    def get_nombrecorto(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for linea in self.browse(cr, uid, ids, context):
            ret[linea.id] = "No Especificado"
            if linea.relation_avance and linea.relation_avance.proyecto:
                ret[linea.id] = linea.relation_avance.proyecto.nombre_corto
        return ret

    def get_current(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            ret[i.id] = i.id
        return ret

    def get_name(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            ret[i.id] = "Avance "
        return ret

    def get_cuestionario(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            ret[i.id] = 0
            if i.tiraje and i.tiraje.cuestionario_id:
                ret[i.id] = i.tiraje.cuestionario_id.id
        return ret

    def aprueba_encuesta(self, cr, uid, ids, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            print("Hola ------------- ")
        return ret

    def pausa_encuesta(self, cr, uid, ids, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            status = not i.stand_by
            self.write(cr, uid, [i.id], {"stand_by": status})
        return ret

    def count_vars(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            count = 0
            for j in i.cuota_ids:
                count += 1
            ret[i.id] = count
        return ret

    def cancela_encuesta(self, cr, uid, ids, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            if i.rechazada:
                return ret
            rechazadas_obj = self.pool.get("ea.rechazadas")
            rechazadas_obj.create(
                cr, uid, {
                    'name': i.name,
                    'investigador': i.empleado.id,
                    'folio': i.folio,
                    'supervisor': i.supervisor.id,
                    'revisor': uid,
                    'fase': i.relation_avance.state,
                    'relation_avance': i.relation_avance.id,
                })
            self.write(cr, uid, [i.id], {'rechazada': True})
            #Generando el descuento
            monto = 0.0
            if i.tiraje and i.tiraje.cuestionario_id:
                print("Entrando -----------  ------------")
                for j in i.tiraje.cuestionario_id.salario_ids:
                    print("Salario " + str(j.id) + " Tipo" + str(j.tipo))
                    print("Id Plaza " + str(j.plaza_id.id) + "vs" +
                          str(i.relation_avance.plaza_id.id))
                    print("Concepto" + str(j.name.name) + "vs" +
                          str(i.concepto.name))
                    print("Revisando" + str((j.tipo) == "propia"))
                    if str(j.tipo) == "propia":
                        print("Tipo OK")
                        if j.plaza_id and j.plaza_id.id is\
                        i.relation_avance.plaza_id.id:
                            print("Plaza OK")
                            if j.name.name is i.concepto.name:
                                print("Concepto OK")
                                print("El monto es" + str(j.monto) +
                                      j.name.name)
                                monto = j.monto
                                break
            descuento_obj = self.pool.get("hr.descuentos")
            descuento_obj.create(
                cr, uid, {
                    'empleado': i.empleado.id,
                    'fecha': i.relation_avance.fecha,
                    'name': "Entrevista cancelada folio" + str(i.folio),
                    'tipo': "monto",
                    'monto': monto,
                    'fecha_reporte': i.relation_avance.fecha,
                    'fase': i.relation_avance.state,
                    'proyecto_id': i.relation_avance.proyecto.id,
                })
        return ret

    def get_idestudio(self, cr, uid, ids, fieldname, args, context=None):
        ret = {}
        for i in self.browse(cr, uid, ids, context):
            ret[i.id] = i.proyecto
        return ret

    _columns = {
        'name':
        fields.char(string="Nombre", size=40, store=True),
        'cantidad':
        fields.integer("Cantidad"),
        'cuestionario':
        fields.many2one('ea.encuesta', string="Cuestionario"),
        'cuota':
        fields.many2one("ea.cuota", string="Cuota"),
        'relation_avance':
        fields.many2one("ea.avance"),
        'empleado':
        fields.many2one("hr.employee", string="Levantó"),
        'supervisor':
        fields.many2one("hr.employee", string="Supervisó"),
        'proyecto':
        fields.function(get_proyecto,
                        string="Proyecto",
                        type="integer",
                        store=True),
        'id_proyecto':
        fields.function(get_proyecto,
                        string="Proyecto",
                        type="char",
                        store=True),
        'project_name':
        fields.function(get_proyecton, string="Clave", type="char",
                        store=True),
        'nombre_corto':
        fields.function(get_nombrecorto,
                        string="Nombre Corto",
                        type="char",
                        store=True),
        'current_id':
        fields.function(get_current, type="integer", string="Id", store=True),
        'cuota_ids':
        fields.many2many('ea.cuota',
                         'avance_cuota_rel',
                         'avance_linea_id',
                         'ea_cuota_id',
                         string='Cuotas'),
        'folio':
        fields.char("Folio"),
        'stand_by':
        fields.boolean("En Pausa"),
        'rechazada':
        fields.boolean("Rechazada"),
        'supervision':
        fields.many2many("ea.tipo_supervision", string="Tipo de Supervisión"),
        'sup_oficina':
        fields.many2many("ea.tipo_supervision",
                         "ofc_sup",
                         "f1",
                         "f2",
                         string="Supervisión de Oficina"),
        'plaza_id':
        fields.function(get_plaza, string="Plaza", type="integer", store=True),
        'plaza_name':
        fields.function(get_plazaname, string="Plaza", type="char",
                        store=True),
        'fecha':
        fields.function(get_fecha, string="Fecha", type="date", store=True),
        'tiraje':
        fields.many2one("ea.tiraje", "Tiraje"),
        'idcuestionario':
        fields.function(get_cuestionario,
                        string="Id Cuestionario",
                        type="char"),
        'concepto':
        fields.many2one("ea.salario.concepto", string="Pago Entrevista"),
        'conteo':
        fields.function(count_vars, string="Variables", type="char"),
        'ntienda':
        fields.char("Nombre Tienda"),
        'sucursal':
        fields.char("Sucursal"),
        'dia_semana':
        fields.selection([('Lunes', 'Lunes'), ('Martes', 'Martes'),
                          ('Miercoles', 'Miercoles'), ('Jueves', 'Jueves'),
                          ('Viernes', 'Viernes'), ('Sabado', 'Sabado'),
                          ('Domingo', 'Domingo')],
                         string="Día de la Semana"),
        'estudioid':
        fields.function(get_idestudio,
                        string="Id Estudio",
                        type="char",
                        store=True),
    }

    _defaults = {'name': "Avance"}
Пример #53
0
    STATE_SELECTION = [
        ('draft', 'Request for Quotation'),
        ('wait', 'Waiting'),
        ('confirmed', 'Waiting Procurement Manager Approve'),
        ('confirmed2', 'Waiting Head of Procurement Division'),
        ('confirmed3', 'Waiting Head of Division Approve'),
        ('confirmed4', 'Waiting CEO Approve'),
        ('approved', 'Approved'),
        ('except_picking', 'Shipping Exception'),
        ('except_invoice', 'Invoice Exception'),
        ('done', 'Done'),
        ('cancel', 'Cancelled')
    ]

    _columns = {
        'state'                 : fields.selection(STATE_SELECTION, 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
        'budget_info_ids_po'    : fields.many2many('budget.info.po', 'budget_info_rel_po', 'order_id', 'budget_info_id_po', 'Budget Line', readonly=True),
        'budget_note'           : fields.text('Budget Note'),
        'budget_note_line_ids'  : fields.one2many('budget.note.po', 'order_id', 'Budget Note History'),
        
        #######DICOUNT#####################
        'amount_untaxed': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Untaxed Amount',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The amount without tax"),
        'amount_tax': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Purchase Price'), string='Taxes',
            store={
                'purchase.order.line': (_get_order, None, 10),
                'purchase.order': (lambda self, cr, uid, ids, c={}: ids, ['discount_total'], 20),
            }, multi="sums", help="The tax amount"),
class vehicles_fuel_details_report(osv.osv):
    _name = "vehicles.fuel.details.report"
    _description = "Purchases Orders"
    _auto = False
    _columns = {
        'date': fields.date('Order Date', readonly=True, help="Date on which this document has been created"),
        'name': fields.char('Year',size=64,required=False, readonly=True),
        'day': fields.char('Day', size=128, readonly=True),
        'product_id':fields.many2one('product.product', 'Product', readonly=True),
        'emp_id' :fields.many2one('hr.employee', 'Employee', readonly=True),
        'department_id':fields.many2one('hr.department', 'Department',readonly=True ),
        'car': fields.many2one('account.asset.asset', 'Car Name',readonly=True),
        'code': fields.related('car', 'plate_no', type='char', relation='account.asset.asset', string='Car Number', readonly=True, store=True),    
        'product_uom' : fields.many2one('product.uom', 'Reference UoM', required=True),
        'company_id':fields.many2one('res.company', 'Company', readonly=True),
        'user_id':fields.many2one('res.users', 'Responsible', readonly=True),
        'quantity': fields.float('Quantity', readonly=True),
        'nbr': fields.integer('# of Lines', 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),
        'category_id': fields.many2one('product.category', 'Category', readonly=True)

    }
    _order = 'name desc'
    def init(self, cr):
        tools.sql.drop_view_if_exists(cr, 'vehicles_fuel_details_report')
        cr.execute("""
            create or replace view vehicles_fuel_details_report as (
                select
                    min(l.id) as id,
                    s.date as date,
                    to_char(s.date, 'YYYY') as name,
                    to_char(s.date, 'MM') as month,
                    to_char(s.date, 'YYYY-MM-DD') as day,
                    s.department_id,
                    s.car,
                    s.code,
                    s.emp_id as emp_id,
                    s.create_uid as user_id,
                    s.company_id as company_id,
                    l.product_id,
                    t.categ_id as category_id,
                    t.uom_id as product_uom,
                    sum(l.product_qty/u.factor*u2.factor) as quantity,
                    count(*) as nbr

                from vehicles_fuel_details s
                    left join fuel_details_lines l on (s.id=l.fuel_id)
                        left join product_product p on (l.product_id=p.id)
                            left join product_template t on (p.product_tmpl_id=t.id)
                    left join product_uom u on (u.id=l.product_uom)
                    left join product_uom u2 on (u2.id=t.uom_id)
                where l.product_id is not null
                group by
                    s.company_id,
                    s.create_uid,
                    s.emp_id,
                    l.product_qty,
                    u.factor,
                    l.product_uom,
                    s.department_id,
                    s.code,
                    s.car,
                    l.product_id,
                    t.categ_id,
                    s.date,
                    to_char(s.date, 'YYYY'),
                    to_char(s.date, 'MM'),
                    to_char(s.date, 'YYYY-MM-DD'),
                    u.uom_type, 
                    u.category_id,
                    t.uom_id,
                    u.id,
                    u2.factor
            )
        """)
Пример #55
0
    def _payment_type_name_get(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for rec in self.browse(cr, uid, ids, context):
            result[rec.id] = rec.mode and rec.mode.type.name or ""
        return result

    def _name_get(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for rec in self.browse(cr, uid, ids, context):
            result[rec.id] = rec.reference
        return result

    _columns = {
        "type": fields.selection(
            [("payable", "Payable"), ("receivable", "Receivable")], "Type", readonly=True, select=True
        ),
        # invisible field to filter payment order lines by payment type
        "payment_type_name": fields.function(
            _payment_type_name_get, method=True, type="char", size=64, string="Payment type name"
        ),
        # The field name is necessary to add attachement documents to payment orders
        "name": fields.function(_name_get, method=True, type="char", size=64, string="Name"),
        "create_account_moves": fields.selection(
            [("bank-statement", "Bank Statement"), ("direct-payment", "Direct Payment")],
            "Create Account Moves",
            required=True,
            states={"done": [("readonly", True)]},
            help='Indicates when account moves should be created for order payment lines. "Bank Statement" '
            'will wait until user introduces those payments in bank a bank statement. "Direct Payment" '
            "will mark all payment lines as payied once the order is done.",
Пример #56
0
class pos_box_entries(osv.osv_memory):
    _name = 'pos.box.entries'
    _description = 'Pos Box Entries'

    #Columns section
    def _select_cash_registers(self, cr, uid, context=None):
        if not context:
            context = {}
        statement_obj = self.pool.get('account.bank.statement')
        session_id = context.get('active_id', False)
        statement_ids = statement_obj.search(
            cr, uid, [('pos_session_id', '=', session_id)], context=context)
        statements = statement_obj.read(cr,
                                        uid,
                                        statement_ids,
                                        ['name', 'id', 'journal_id'],
                                        context=context)
        result = [(st['id'], st['journal_id'][1] + ' - (' + st['name'] + ')')
                  for st in statements]
        return result

    _columns = {
        'name':
        fields.related("product_id", "name", type='char', store=True),
        'statement_id':
        fields.selection(
            _select_cash_registers,
            string="Cash Register",
            type="many2one",
            relation="account.bank.statement",
            method=True,
            required=True,
        ),
        'session_id':
        fields.many2one(
            "pos.session",
            "session",
        ),
        'product_id':
        fields.many2one(
            "product.product",
            "Operation",
            required=True,
        ),
        'amount':
        fields.float('Amount',
                     digits=(16, 2),
                     required=True,
                     help="The amount you take in your cash register"),
        'ref':
        fields.char('Ref', size=32),
    }

    _defaults = {
        'session_id':
        lambda self, cr, uid, context: context.get('active_id', False),
    }

    #Private section
    def get_in(self, cr, uid, ids, context=None):
        """
             Create the entry of statement in journal.
             @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 of operation of product
        """
        statement_obj = self.pool.get('account.bank.statement')
        res_obj = self.pool.get('res.users')
        product_obj = self.pool.get('product.product')
        bank_statement = self.pool.get('account.bank.statement.line')
        for pbe in self.browse(cr, uid, ids, context=context):
            vals = {}
            curr_company = res_obj.browse(cr, uid, uid,
                                          context=context).company_id.id
            statement_id = pbe.statement_id
            if not statement_id:
                raise osv.except_osv(
                    _('Error !'), _('You have to open at least one cashbox'))

            product = pbe.product_id
            acc_id = product.property_account_income or product.categ_id.property_account_income_categ
            if not acc_id:
                raise osv.except_osv(
                    _('Error !'),
                    _('Please check that income account is set to %s') %
                    (product_obj.browse(cr, uid, data['product_id']).name))
            statement = statement_obj.browse(cr,
                                             uid,
                                             int(statement_id),
                                             context=context)
            vals['statement_id'] = statement_id
            vals['journal_id'] = int(statement.journal_id.id)
            if acc_id:
                vals['account_id'] = acc_id.id
            if pbe.amount > 0:
                vals['amount'] = pbe.amount
            else:
                vals['amount'] = -pbe.amount
            vals['ref'] = "%s" % (pbe.name or '')
            vals['name'] = "%s " % (pbe.name or '')
            bank_statement.create(cr, uid, vals, context=context)
        return {}
Пример #57
0
        #   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, method=True,
            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),
        'dependencies_id': fields.one2many('ir.module.module.dependency',
            'module_id', 'Dependencies', readonly=True),
        'web_dependencies_id': fields.one2many('ir.module.web.dependency',
            'module_id', 'Web Dependencies', readonly=True),
        '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),
        'demo': fields.boolean('Demo data'),
        'license': fields.selection([
                ('GPL-2', 'GPL Version 2'),
                ('GPL-2 or any later version', 'GPL-2 or later version'),
                ('GPL-3', 'GPL Version 3'),
                ('GPL-3 or any later version', 'GPL-3 or later version'),
                ('AGPL-3', 'Affero GPL-3'),
                ('Other OSI approved licence', 'Other OSI Approved Licence'),
                ('Other proprietary', 'Other Proprietary')
            ], string='License', readonly=True),
        'menus_by_module': fields.function(_get_views, method=True, string='Menus', type='text', multi="meta", store=True),
        'reports_by_module': fields.function(_get_views, method=True, string='Reports', type='text', multi="meta", store=True),
Пример #58
0
class hr_evaluation_report(osv.osv):
    _name = "hr.evaluation.report"
    _description = "Evaluations Statistics"
    _auto = False
    _rec_name = 'date'
    _columns = {
        'create_date':
        fields.date('Create Date', readonly=True),
        'delay_date':
        fields.float('Delay to Start', digits=(16, 2), readonly=True),
        'overpass_delay':
        fields.float('Overpassed Deadline', digits=(16, 2), readonly=True),
        'progress_bar':
        fields.float("Progress"),
        'day':
        fields.char('Day', size=128, readonly=True),
        'deadline':
        fields.date("Deadline", readonly=True),
        'request_id':
        fields.many2one('survey.request', 'Request_id', readonly=True),
        'closed':
        fields.date("closed", readonly=True),
        'year':
        fields.char('Year', size=4, 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),
        'plan_id':
        fields.many2one('hr_evaluation.plan', 'Plan', readonly=True),
        'employee_id':
        fields.many2one('hr.employee', "Employee", readonly=True),
        'rating':
        fields.selection([
            ('0', 'Significantly bellow expectations'),
            ('1', 'Did not meet expectations'),
            ('2', 'Meet expectations'),
            ('3', 'Exceeds expectations'),
            ('4', 'Significantly exceeds expectations'),
        ],
                         "Overall Rating",
                         readonly=True),
        'nbr':
        fields.integer('# of Requests', readonly=True),
        'state':
        fields.selection([
            ('draft', 'Draft'),
            ('wait', 'Plan In Progress'),
            ('progress', 'Final Validation'),
            ('done', 'Done'),
            ('cancel', 'Cancelled'),
        ],
                         'State',
                         readonly=True),
    }
    _order = 'create_date desc'

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'hr_evaluation_report')
        cr.execute("""
            create or replace view hr_evaluation_report as (
                 select
                     min(l.id) as id,
                     date_trunc('day',s.create_date) as create_date,
                     to_char(s.create_date, 'YYYY-MM-DD') as day,
                     s.employee_id,
                     l.request_id,
                     s.plan_id,
                     s.rating,
                     s.date as deadline,
                     s.date_close as closed,
                     to_char(s.create_date, 'YYYY') as year,
                     to_char(s.create_date, 'MM') as month,
                     count(l.*) as nbr,
                     s.state,
                     s.progress as progress_bar,
                     avg(extract('epoch' from age(s.create_date,CURRENT_DATE)))/(3600*24) as  delay_date,
                     avg(extract('epoch' from age(s.date,CURRENT_DATE)))/(3600*24) as overpass_delay
                     from
                 hr_evaluation_interview l
                LEFT JOIN
                     hr_evaluation_evaluation s on (s.id=l.evaluation_id)
                 GROUP BY
                     s.create_date,
                     date_trunc('day',s.create_date),
                     to_char(s.create_date, 'YYYY-MM-DD'),
                     to_char(s.create_date, 'YYYY'),
                     to_char(s.create_date, 'MM'),
                     s.state,
                     s.employee_id,
                     s.date,
                     s.date_close,
                     l.request_id,
                     s.rating,
                     s.progress,
                     s.plan_id
            )
        """)
Пример #59
0
        return result

    def _get_extras(self, cr, uid, ids, *args, **kwargs):
        result = []
        if aeroo_ooo_test(cr):
            result.append('aeroo_ooo')
        ##### Check deferred_processing module #####
        cr.execute("SELECT id, state FROM ir_module_module WHERE name='deferred_processing'")
        deferred_proc_module = cr.dictfetchone()
        if deferred_proc_module and deferred_proc_module['state'] in ('installed', 'to upgrade'):
            result.append('deferred_processing')
        ############################################
        return dict.fromkeys(ids, ','.join(result))

    _columns = {
        'charset':fields.selection(_get_encodings, string='Charset', required=True),
        'content_fname': fields.char('Override Extension',size=64, help='Here you can override output file extension'),
        'styles_mode': fields.selection([
            ('default','Not used'),
            ('global', 'Global'),
            ('specified', 'Specified'),
            ], string='Stylesheet'),
        'stylesheet_id':fields.many2one('report.stylesheets', 'Template Stylesheet'),
        'preload_mode':fields.selection([
            ('static',_('Static')),
            ('preload',_('Preload')),
        ],'Preload Mode'),
        'tml_source':fields.selection([
            ('database','Database'),
            ('file','File'),
            ('parser','Parser'),
class medical_patient(osv.osv):
    _name = "medical.patient"
    _inherit = "medical.patient"
    _columns = {
        'excercise':
        fields.boolean('Excersise'),
        'excercise_minutes_day':
        fields.integer('Minutes / day',
                       help="How many minutes a day the patient excersises"),
        'sleep_hours':
        fields.integer('Hours of sleep',
                       help="Average hours of sleep per day"),
        'sleep_during_daytime':
        fields.boolean(
            'Sleeps at daytime',
            help=
            "Check if the patient sleep hours are during daylight rather than at night"
        ),
        'number_of_meals':
        fields.integer('Meals per day'),
        'eats_alone':
        fields.boolean(
            'Eats alone',
            help="Check this box if the patient eats by him / herself."),
        'salt':
        fields.boolean('Salt',
                       help="Check if patient consumes salt with the food"),
        'coffee':
        fields.boolean('Coffee'),
        'coffee_cups':
        fields.integer('Cups per day', help="Number of cup of coffee a day"),
        'soft_drinks':
        fields.boolean(
            'Soft drinks (sugar)',
            help="Check if the patient consumes soft drinks with sugar"),
        'diet':
        fields.boolean('Currently on a diet',
                       help="Check if the patient is currently on a diet"),
        'diet_info':
        fields.char('Diet info',
                    size=256,
                    help="Short description on the diet"),
        'smoking':
        fields.boolean('Smokes'),
        'smoking_number':
        fields.integer('Cigarretes a day'),
        'ex_smoker':
        fields.boolean('Ex-smoker'),
        'second_hand_smoker':
        fields.boolean(
            'Passive smoker',
            help="Check it the patient is a passive / second-hand smoker"),
        'age_start_smoking':
        fields.integer('Age started to smoke'),
        'age_quit_smoking':
        fields.integer('Age of quitting', help="Age of quitting smoking"),
        'alcohol':
        fields.boolean('Drinks Alcohol'),
        'age_start_drinking':
        fields.integer('Age started to drink ', help="Date to start drinking"),
        'age_quit_drinking':
        fields.integer('Age quit drinking ', help="Date to stop drinking"),
        'ex_alcoholic':
        fields.boolean('Ex alcoholic'),
        'alcohol_beer_number':
        fields.integer('Beer / day'),
        'alcohol_wine_number':
        fields.integer('Wine / day'),
        'alcohol_liquor_number':
        fields.integer('Liquor / day'),
        'drug_usage':
        fields.boolean('Drug Habits'),
        'ex_drug_addict':
        fields.boolean('Ex drug addict'),
        'drug_iv':
        fields.boolean('IV drug user',
                       help="Check this option if the patient injects drugs"),
        'age_start_drugs':
        fields.integer('Age started drugs ', help="Age of start drugs"),
        'age_quit_drugs':
        fields.integer('Age quit drugs ', help="Date of quitting drugs"),
        'drugs':
        fields.many2many('medical.drugs_recreational',
                         'patient_drugs_recreational_rel',
                         'patient_id',
                         'drugs_recreational_id',
                         'Drugs',
                         help="Name of drugs that the patient consumes"),
        'traffic_laws':
        fields.boolean('Obeys Traffic Laws',
                       help="Check if the patient is a safe driver"),
        'car_revision':
        fields.boolean(
            'Car Revision',
            help=
            "Maintain the vehicle. Do periodical checks - tires, engine, breaks ..."
        ),
        'car_seat_belt':
        fields.boolean('Seat belt',
                       help="Safety measures when driving : safety belt"),
        'car_child_safety':
        fields.boolean(
            'Car Child Safety',
            help=
            "Safety measures when driving : child seats, proper seat belting, not seating on the front seat, ...."
        ),
        'home_safety':
        fields.boolean(
            'Home safety',
            help=
            "Keep safety measures for kids in the kitchen, correct storage of chemicals, ..."
        ),
        'motorcycle_rider':
        fields.boolean('Motorcycle Rider',
                       help="The patient rides motorcycles"),
        'helmet':
        fields.boolean('Uses helmet',
                       help="The patient uses the proper motorcycle helmet"),
        'lifestyle_info':
        fields.text('Extra Information'),
        'sexual_preferences':
        fields.selection([
            ('h', 'Heterosexual'),
            ('g', 'Homosexual'),
            ('b', 'Bisexual'),
            ('t', 'Transexual'),
        ], 'Sexual Orientation'),
        'sexual_practices':
        fields.selection([
            ('s', 'Safe / Protected sex'),
            ('r', 'Risky / Unprotected sex'),
        ], 'Sexual Practices'),
        'sexual_partners':
        fields.selection([
            ('m', 'Monogamous'),
            ('t', 'Polygamous'),
        ], 'Sexual Partners'),
        'sexual_partners_number':
        fields.integer('Number of sexual partners'),
        'first_sexual_encounter':
        fields.integer('Age first sexual encounter'),
        'anticonceptive':
        fields.selection([
            ('0', 'None'),
            ('1', 'Pill / Minipill'),
            ('2', 'Male condom'),
            ('3', 'Vasectomy'),
            ('4', 'Female sterilisation'),
            ('5', 'Intra-uterine device'),
            ('6', 'Withdrawal method'),
            ('7', 'Fertility cycle awareness'),
            ('8', 'Contraceptive injection'),
            ('9', 'Skin Patch'),
            ('10', 'Female condom'),
        ], 'Anticonceptive Method'),
        'sex_oral':
        fields.selection([
            ('0', 'None'),
            ('1', 'Active'),
            ('2', 'Passive'),
            ('3', 'Both'),
        ], 'Oral Sex'),
        'sex_anal':
        fields.selection([
            ('0', 'None'),
            ('1', 'Active'),
            ('2', 'Passive'),
            ('3', 'Both'),
        ], 'Anal Sex'),
        'prostitute':
        fields.boolean(
            'Prostitute',
            help="Check if the patient (he or she) is a prostitute"),
        'sex_with_prostitutes':
        fields.boolean(
            'Sex with prostitutes',
            help="Check if the patient (he or she) has sex with prostitutes"),
        'sexuality_info':
        fields.text('Extra Information'),
    }