Example #1
0
 def create_label(self, name, markup=False, align=1.0, wrap=False,
                  angle=None, width=None, fname=None, help=None, detail_tooltip=False):
     
     label = gtk.Label(name)
     eb = gtk.EventBox()
     eb.set_events(gtk.gdk.BUTTON_PRESS_MASK)
     if markup:
         label.set_use_markup(True)
     self.trans_box_label.append((eb, name, fname))
     eb.add(label)
     
     def size_allocate(label, allocation):
         label.set_size_request( allocation.width - 2, -1 )
     if fname is None and name and len(name) > 50:
         label.connect( "size-allocate", size_allocate )
     uid = rpc.session.uid
     tooltip = ''
     if help:
         tooltip = '<span foreground="darkred"><b>%s</b></span>\n%s' % \
                     (tools.to_xml(name), tools.to_xml(help))
         label.set_markup('<sup><span foreground="darkgreen">?</span></sup>' + tools.to_xml(name))
     if detail_tooltip:
         tooltip += (help and '\n' or '') + detail_tooltip
     if tooltip:
         eb.set_tooltip_markup(tooltip)
     label.set_alignment(align, 0.5)
     if width:
         label.set_size_request(width, -1)
     label.set_line_wrap(bool(int(wrap)))
     if angle:
         label.set_angle(int(angle))
     return eb
Example #2
0
        def process_bom(bom, currency_id, factor=1):
            xml = '<row>'
            sum = 0
            sum_strd = 0
            prod = product_pool.browse(cr, uid, bom['product_id'])
            prod_name = to_xml(bom['name'])
            prod_qtty = factor * bom['product_qty']
            product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context)
            product_uom_name = to_xml(product_uom.name)
            main_sp_price, main_sp_name , main_strd_price = '','',''
            sellers, sellers_price = '',''

            if prod.seller_id:
                main_sp_name = '- <b>'+ to_xml(prod.seller_id.name) +'</b>\r\n'
                price = supplier_info_pool.price_get(cr, uid, prod.seller_id.id, prod.id, number*prod_qtty)[prod.seller_id.id]
                price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, price, to_uom_id=product_uom.id)
                main_sp_price = """<b>"""+rml_obj.formatLang(price)+' '+ company_currency.symbol+"""</b>\r\n"""
                sum += prod_qtty*price
            std_price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, prod.standard_price, to_uom_id=product_uom.id)
            main_strd_price = str(std_price) + '\r\n'
            sum_strd = prod_qtty*std_price
            for seller_id in prod.seller_ids:
                sellers +=  '- <i>'+ to_xml(seller_id.name.name) +'</i>\r\n'
                price = supplier_info_pool.price_get(cr, uid, seller_id.name.id, prod.id, number*prod_qtty)[seller_id.name.id]
                price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, price, to_uom_id=product_uom.id)
                sellers_price += """<i>"""+rml_obj.formatLang(price) +' '+ company_currency.symbol +"""</i>\r\n"""
            xml += """<col para='yes'> """+ prod_name +""" </col>
                    <col para='yes'> """+ main_sp_name + sellers + """ </col>
                    <col f='yes'>"""+ rml_obj.formatLang(prod_qtty) +' '+ product_uom_name +"""</col>
                    <col f='yes'>"""+ rml_obj.formatLang(float(main_strd_price)) +' '+ company_currency.symbol +"""</col>
                    <col f='yes'>""" + main_sp_price + sellers_price + """</col>'"""

            xml += '</row>'
            return xml, sum, sum_strd
Example #3
0
    def wid_add(self,
                widget,
                colspan=1,
                name=None,
                expand=False,
                xoptions=False,
                ypadding=0,
                help=False,
                rowspan=1):
        self.count += 1
        (table, x, y) = self.cont[-1]
        if name:
            vbox = gtk.VBox(homogeneous=False, spacing=2)
            label = gtk.Label(name)
            label.set_alignment(0.0, 0.0)
            if help:
                try:
                    vbox.set_tooltip_markup(
                        '<span foreground=\"darkred\"><b>' +
                        tools.to_xml(name) + '</b></span>\n' +
                        tools.to_xml(help))
                except:
                    pass
                label.set_markup(
                    "<sup><span foreground=\"darkgreen\">?</span></sup>" +
                    tools.to_xml(name))
            vbox.pack_start(label, expand=False)
            vbox.pack_start(widget, expand=expand, fill=False)
            wid = vbox
            wid.set_border_width(2)
        else:
            wid = widget
            if help:
                try:
                    wid.set_tooltip_markup(
                        '<span foreground=\"darkred\"></span>' +
                        tools.to_xml(help))
                except:
                    pass

        yopt = False
        if expand:
            yopt = yopt | gtk.EXPAND | gtk.FILL
        if not xoptions:
            xoptions = gtk.FILL | gtk.EXPAND
        table.attach(wid,
                     x,
                     x + colspan,
                     y,
                     y + rowspan,
                     yoptions=yopt,
                     xoptions=xoptions,
                     ypadding=ypadding,
                     xpadding=0)
        self.cont[-1] = (table, x + colspan, y)
        wid_list = table.get_children()
        wid_list.reverse()
        table.set_focus_chain(wid_list)
        return wid
Example #4
0
        def process_bom(bom, currency_id, factor=1):
            xml = '<row>'
            sum = 0
            sum_strd = 0
            prod = product_pool.browse(cr, uid, bom['product_id'])

            prod_name = to_xml(bom['name'])
            prod_qtty = factor * bom['product_qty']
            product_uom = product_uom_pool.browse(cr,
                                                  uid,
                                                  bom['product_uom'],
                                                  context=context)
            product_uom_name = to_xml(product_uom.name)
            main_sp_price, main_sp_name, main_strd_price = '', '', ''
            sellers, sellers_price = '', ''

            if prod.seller_id:
                main_sp_name = '- <b>' + to_xml(
                    prod.seller_id.name) + '</b>\r\n'
                pricelist = prod.seller_id.property_product_pricelist_purchase
                price = pricelist_pool.price_get(
                    cr, uid, [pricelist.id], prod.id, number * prod_qtty
                    or 1.0, prod.seller_id.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                    })[pricelist.id]
                main_sp_price = """<b>""" + rml_obj.formatLang(price) + ' ' + (
                    company_currency_symbol) + """</b>\r\n"""
                sum += prod_qtty * price
            std_price = product_uom_pool._compute_price(
                cr,
                uid,
                prod.uom_id.id,
                prod.standard_price,
                to_uom_id=product_uom.id)
            main_strd_price = str(std_price) + '\r\n'
            sum_strd = prod_qtty * std_price
            for seller_id in prod.seller_ids:
                sellers += '- <i>' + to_xml(seller_id.name.name) + '</i>\r\n'
                pricelist = seller_id.name.property_product_pricelist_purchase
                price = pricelist_pool.price_get(
                    cr, uid, [pricelist.id], prod.id, number * prod_qtty
                    or 1.0, seller_id.name.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                    })[pricelist.id]
                sellers_price += """<i>""" + rml_obj.formatLang(
                    price) + ' ' + (company_currency_symbol) + """</i>\r\n"""
            xml += """<col para='yes'> """ + prod_name + """ </col>
                    <col para='yes'> """ + main_sp_name + sellers + """ </col>
                    <col f='yes'>""" + rml_obj.formatLang(
                prod_qtty) + ' ' + product_uom_name + """</col>
                    <col f='yes'>""" + rml_obj.formatLang(
                    float(main_strd_price)) + ' ' + (
                        company_currency_symbol) + """</col>
                    <col f='yes'>""" + main_sp_price + sellers_price + """</col>'"""

            xml += '</row>'
            return xml, sum, sum_strd
Example #5
0
 def create_detail_tooltip(self, name='', field_attr={}):
     tooltip = '<span foreground="#009900"><b>%s:</b> %s - <b>%s:</b> %s' % \
             (_('Field'), tools.to_xml(name), _('Object'), tools.to_xml(field_attr.get('model','')))
     attributes = field_attr.keys()
     attributes.sort()
     for attr in attributes:
         if attr in self.accepted_attr_list:
             tooltip += '\n<b>%s:</b> %s' %(tools.to_xml(str(attr).capitalize()),tools.to_xml(str(field_attr[attr])))
     return tooltip + '</span>'
Example #6
0
 def create_detail_tooltip(self, name='', field_attr={}):
     tooltip = '<span foreground="#009900"><b>%s:</b> %s - <b>%s:</b> %s' % \
             (_('Field'), tools.to_xml(name), _('Object'), tools.to_xml(field_attr.get('model','')))
     attributes = field_attr.keys()
     attributes.sort()
     for attr in attributes:
         if attr in self.accepted_attr_list:
             tooltip += '\n<b>%s:</b> %s' % (tools.to_xml(
                 str(attr).capitalize()), tools.to_xml(str(
                     field_attr[attr])))
     return tooltip + '</span>'
    def fields_view_get(self, cr, uid, view_id=None, view_type="form", context=None, toolbar=False):
        wiz_id = self.pool.get("ir.actions.wizard").search(cr, uid, [("wiz_name", "=", "create.model")])
        res = super(account_analytic_plan_instance, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar)

        if res["type"] == "form":
            plan_id = False
            if context.get("journal_id", False):
                plan_id = self.pool.get("account.journal").browse(cr, uid, int(context["journal_id"]), context).plan_id
            elif context.get("plan_id", False):
                plan_id = self.pool.get("account.analytic.plan").browse(cr, uid, int(context["plan_id"]), context)

            if plan_id:
                i = 1
                res[
                    "arch"
                ] = """<form string="%s">
    <field name="name"/>
    <field name="code"/>
    <field name="journal_id"/>
    <button name="%d" string="Save This Distribution as a Model" type="action" colspan="2"/>
    """ % (
                    tools.to_xml(plan_id.name),
                    wiz_id[0],
                )
                for line in plan_id.plan_ids:
                    res[
                        "arch"
                    ] += """
                    <field name="account%d_ids" string="%s" colspan="4">
                    <tree string="%s" editable="bottom">
                        <field name="rate"/>
                        <field name="analytic_account_id" domain="[('parent_id','child_of',[%d])]"/>
                    </tree>
                </field>
                <newline/>""" % (
                        i,
                        tools.to_xml(line.name),
                        tools.to_xml(line.name),
                        line.root_analytic_id and line.root_analytic_id.id or 0,
                    )
                    i += 1
                res["arch"] += "</form>"
                doc = etree.fromstring(res["arch"].encode("utf8"))
                xarch, xfields = self._view_look_dom_arch(cr, uid, doc, view_id, context=context)
                res["arch"] = xarch
                res["fields"] = xfields
            return res
        else:
            return res
Example #8
0
 def __init__(self, name, parent, attrs={}, call=None):
     wid_int.wid_int.__init__(self, name, parent, attrs, call)
     if name:
         self.butt = gtk.ToggleButton(name)
         if len(name) < 10:
             self.butt.set_size_request(90, -1)
     else:
         self.butt = gtk.ToggleButton()
         self.butt.set_relief(gtk.RELIEF_NONE)
     icon = gtk.Image()
     icon.set_from_stock(attrs.get('icon', 'gtk-home'), 1)
     self.butt.set_image(icon)
     self.butt.set_image_position(gtk.POS_TOP)
     self.butt.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("grey"))
     self.butt.modify_bg(gtk.STATE_PRELIGHT,
                         gtk.gdk.color_parse("light grey"))
     help = attrs.get('help', False) or attrs.get('string', False)
     if help:
         self.butt.set_tooltip_markup(tools.to_xml(help))
     self.domain = attrs.get('domain', "[]")
     self.context = attrs.get('context', "{}")
     if self.default_search:
         self.butt.set_active(True)
     self.butt.set_alignment(0.5, 0.5)
     self.butt.connect('toggled', call[1])
     self.screen_context = call[0].context
     self.widget = self.butt
Example #9
0
 def __init__(self, name, parent, attrs={}, call=None):
     wid_int.wid_int.__init__(self, name, parent, attrs,call)
     if name:
         self.butt = gtk.ToggleButton(name)
         if len(name) < 10:
             self.butt.set_size_request(90,-1)
     else:
         self.butt = gtk.ToggleButton()
         self.butt.set_relief(gtk.RELIEF_NONE)
     icon = gtk.Image()
     self.name = name or attrs.get('string')
     icon_to_set = attrs.get('icon','gtk-home')
     if icon_to_set.startswith('STOCK'):
         icon_to_set = getattr(gtk, icon_to_set)
     icon.set_from_stock(icon_to_set, 1)
     self.butt.set_image(icon)
     self.butt.set_image_position(gtk.POS_TOP)
     self.butt.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("grey"))
     self.butt.modify_bg(gtk.STATE_PRELIGHT, gtk.gdk.color_parse("light grey"))
     help = attrs.get('help', False) or attrs.get('string', False)
     if help:
         self.butt.set_tooltip_markup(tools.to_xml(help))
     self.domain = attrs.get('domain', "[]")
     self.context = attrs.get('context', "{}")
     if self.default_search:
         self.butt.set_active(True)
     self.butt.set_alignment(0.5, 0.5)
     self.butt.connect('toggled', call[1])
     self.screen_context = call[0].context
     self.widget = self.butt
Example #10
0
    def wid_add(self, widget, name=None, expand=False, ypadding=2, rowspan=1,
            colspan=1, translate=False, fname=None, help=False, fill=False, invisible=False):
        (table, x, y) = self.cont[-1]
        if colspan>self.col[-1]:
            colspan=self.col[-1]
        a = name and 1 or 0
        if colspan+x+a>self.col[-1]:
            self.newline()
            (table, x, y) = self.cont[-1]
        yopt = False
        if expand:
            yopt = yopt | gtk.EXPAND
        if fill:
            yopt = yopt | gtk.FILL
        if colspan == 1 and a == 1:
            colspan = 2
        if name:
            label = gtk.Label(name)
            eb = gtk.EventBox()
            eb.set_events(gtk.gdk.BUTTON_PRESS_MASK)
            self.trans_box_label.append((eb, name, fname))
            eb.add(label)
            if help:
                try:
                    eb.set_tooltip_markup('<span foreground=\"darkred\"><b>'+tools.to_xml(name)+'</b></span>\n'+tools.to_xml(help))
                except:
                    pass
                label.set_markup("<sup><span foreground=\"darkgreen\">?</span></sup>"+tools.to_xml(name))
                eb.show()
            if '_' in name:
                label.set_text_with_mnemonic(name)
                label.set_mnemonic_widget(widget)
            label.set_alignment(1.0, 0.5)
            table.attach(eb, x, x+1, y, y+rowspan, yoptions=yopt,
                    xoptions=gtk.FILL, ypadding=ypadding, xpadding=2)
        hbox = widget
        hbox.show_all()
        if translate:
            hbox = gtk.HBox(spacing=3)
            hbox.pack_start(widget)
            img = gtk.Image()
            img.set_from_stock('terp-translate', gtk.ICON_SIZE_MENU)
            ebox = gtk.EventBox()
            ebox.set_events(gtk.gdk.BUTTON_PRESS_MASK)
            self.trans_box.append((ebox, name, fname, widget))

            ebox.add(img)
            hbox.pack_start(ebox, fill=False, expand=False)
            hbox.show_all()
        table.attach(hbox, x+a, x+colspan, y, y+rowspan, yoptions=yopt,
                ypadding=ypadding, xpadding=2)
        self.cont[-1] = (table, x+colspan, y)
        wid_list = table.get_children()
        wid_list.reverse()
        table.set_focus_chain(wid_list)
        if invisible:
            hbox.hide()
Example #11
0
    def create_label(self,
                     name,
                     markup=False,
                     align=1.0,
                     wrap=False,
                     angle=None,
                     width=None,
                     fname=None,
                     help=None,
                     detail_tooltip=False):

        label = gtk.Label(name)
        eb = gtk.EventBox()
        eb.set_events(gtk.gdk.BUTTON_PRESS_MASK)
        if markup:
            label.set_use_markup(True)
        self.trans_box_label.append((eb, name, fname))
        eb.add(label)

        def size_allocate(label, allocation):
            label.set_size_request(allocation.width - 2, -1)

        if fname is None and name and len(name) > 50:
            label.connect("size-allocate", size_allocate)
        uid = rpc.session.uid
        tooltip = ''
        if help:
            tooltip = '<span foreground="darkred"><b>%s</b></span>\n%s' % \
                        (tools.to_xml(name), tools.to_xml(help))
            label.set_markup(
                '<sup><span foreground="darkgreen">?</span></sup>' +
                tools.to_xml(name))
        if detail_tooltip:
            tooltip += (help and '\n' or '') + detail_tooltip
        if tooltip:
            eb.set_tooltip_markup(tooltip)
        label.set_alignment(align, 0.5)
        if width:
            label.set_size_request(width, -1)
        label.set_line_wrap(bool(int(wrap)))
        if angle:
            label.set_angle(int(angle))
        return eb
Example #12
0
        def process_bom(bom, currency_id, factor=1):
            xml = '<row>'
            sum = 0
            sum_strd = 0
            prod = product_pool.browse(cr, uid, bom['product_id'])

            prod_name = to_xml(bom['name'])
            prod_qtty = factor * bom['product_qty']
            product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context)
            product_uom_name = to_xml(product_uom.name)
            main_sp_price, main_sp_name , main_strd_price = '','',''
            sellers, sellers_price = '',''

            if prod.seller_id:
                main_sp_name = '- <b>'+ to_xml(prod.seller_id.name) +'</b>\r\n'
                pricelist =  prod.seller_id.property_product_pricelist_purchase
                price = pricelist_pool.price_get(cr,uid,[pricelist.id],
                     prod.id, number*prod_qtty or 1.0, prod.seller_id.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                        })[pricelist.id]
                main_sp_price = """<b>"""+rml_obj.formatLang(price)+' '+ (company_currency_symbol)+"""</b>\r\n"""
                sum += prod_qtty*price
            std_price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, prod.cost_price, to_uom_id=product_uom.id)
            main_strd_price = str(std_price) + '\r\n'
            sum_strd = prod_qtty*std_price
            for seller_id in prod.seller_ids:
                sellers +=  '- <i>'+ to_xml(seller_id.name.name) +'</i>\r\n'
                pricelist = seller_id.name.property_product_pricelist_purchase
                price = pricelist_pool.price_get(cr,uid,[pricelist.id],
                     prod.id, number*prod_qtty or 1.0, seller_id.name.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                        })[pricelist.id]
                sellers_price += """<i>"""+rml_obj.formatLang(price) +' '+ (company_currency_symbol) +"""</i>\r\n"""
            xml += """<col para='yes'> """+ prod_name +""" </col>
                    <col para='yes'> """+ main_sp_name + sellers + """ </col>
                    <col f='yes'>"""+ rml_obj.formatLang(prod_qtty) +' '+ product_uom_name +"""</col>
                    <col f='yes'>"""+ rml_obj.formatLang(float(main_strd_price)) +' '+ (company_currency_symbol) +"""</col>
                    <col f='yes'>""" + main_sp_price + sellers_price + """</col>'"""

            xml += '</row>'
            return xml, sum, sum_strd
Example #13
0
 def display(self, widget):
     if self.treeview:
         if self.value:
             self.treeview.warn(
                 'misc-message',
                 '<b>' + str(tools.to_xml(self.value)) + "</b>")
         else:
             self.treeview.warn(
                 'misc-message',
                 _("Press <i>'+'</i>, <i>'-'</i> or <i>'='</i> for special date operations."
                   ))
Example #14
0
    def __init__(self, name, parent, attrs={}, call=None):
        wid_int.wid_int.__init__(self, name, parent, attrs)
        win_gl = glade.XML(common.terp_path("openerp.glade"),"hbox_custom_filter",gettext.textdomain())
        self.widget = win_gl.get_widget('hbox_custom_filter')

        #Changing the date format when using custom filter         
        self.Dt_Tm_format = tools.user_locale_format.get_datetime_format(True)
        self.Dt_format = tools.user_locale_format.get_date_format()
        
        # Processing fields
        self.combo_fields = win_gl.get_widget('combo_fields')
        self.field_selection = {}

        fields = attrs.get('fields',None)
        for item in fields:
            self.field_selection[item[1].encode('utf-8')] = (item[0], item[2], item[3])
            self.combo_fields.append_text(item[1])
        self.combo_fields.set_active(0)

        # Processing operator combo
        self.combo_op = win_gl.get_widget('combo_operator')
        self.op_selection = {}

        for item in (['ilike', _('contains')],
                ['not ilike', _('doesn\'t contain')],
                ['=', _('is equal to')],
                ['<>',_('is not equal to')],
                ['>',_('greater than')],
                ['<',_('less than')],
                ['in',_('in')],
                ['not in',_('not in')],
                ):
            self.op_selection[item[1].encode('utf-8')] = item[0]
            self.combo_op.append_text(item[1])
        self.combo_op.set_active(0)

        # Processing text value
        self.right_text = win_gl.get_widget('right_compare')
        # Processing Custom conditions
        self.condition_next = win_gl.get_widget('cond_custom')
        self.condition_next.set_active(0)

        self.condition_next.hide()
        # Processing Removal of panel
        self.remove_filter = win_gl.get_widget('remove_custom')
        self.remove_filter.set_relief(gtk.RELIEF_NONE)

        try:
            self.right_text.set_tooltip_markup(tools.to_xml(_("Enter Values separated by ',' if operator 'in' or 'not in' is chosen.\nFor Date and DateTime Formats, specify text in '%Y-%m-%d' and '%Y-%m-%d %H:%M:%S' formats respectively.")))
        except:
            pass

        self.remove_filter.connect('clicked',call,self)
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if context is None:
            context = {}
        wiz_id = self.pool.get('ir.actions.act_window').search(cr, uid, [("name","=","analytic.plan.create.model.action")], context=context)
        res = super(account_analytic_plan_instance,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
        journal_obj = self.pool.get('account.journal')
        analytic_plan_obj = self.pool.get('account.analytic.plan')
        if (res['type']=='form'):
            plan_id = False
            if context.get('journal_id', False):
                plan_id = journal_obj.browse(cr, uid, int(context['journal_id']), context=context).plan_id
            elif context.get('plan_id', False):
                plan_id = analytic_plan_obj.browse(cr, uid, int(context['plan_id']), context=context)

            if plan_id:
                i=1
                res['arch'] = """<form string="%s">
    <field name="name"/>
    <field name="code"/>
    <field name="journal_id"/>
    <button name="%d" string="Save This Distribution as a Model" type="action" colspan="2"/>
    """% (tools.to_xml(plan_id.name), wiz_id[0])
                for line in plan_id.plan_ids:
                    res['arch']+="""
                    <field name="account%d_ids" string="%s" nolabel="1" colspan="4">
                    <tree string="%s" editable="bottom">
                        <field name="rate"/>
                        <field name="analytic_account_id" domain="[('parent_id','child_of',[%d])]" groups="base.group_extended"/>
                    </tree>
                </field>
                <newline/>"""%(i,tools.to_xml(line.name),tools.to_xml(line.name),line.root_analytic_id and line.root_analytic_id.id or 0)
                    i+=1
                res['arch'] += "</form>"
                doc = etree.fromstring(res['arch'].encode('utf8'))
                xarch, xfields = self._view_look_dom_arch(cr, uid, doc, view_id, context=context)
                res['arch'] = xarch
                res['fields'] = xfields
            return res
        else:
            return res
Example #16
0
    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        if context is None:
            context = {}
        wiz_id = self.pool.get('ir.actions.act_window').search(cr, uid, [("name","=","analytic.plan.create.model.action")], context=context)
        res = super(account_analytic_plan_instance,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
        journal_obj = self.pool.get('account.journal')
        analytic_plan_obj = self.pool.get('account.analytic.plan')
        if (res['type']=='form'):
            plan_id = False
            if context.get('journal_id', False):
                plan_id = journal_obj.browse(cr, uid, int(context['journal_id']), context=context).plan_id
            elif context.get('plan_id', False):
                plan_id = analytic_plan_obj.browse(cr, uid, int(context['plan_id']), context=context)

            if plan_id:
                i=1
                res['arch'] = """<form string="%s">
    <field name="name"/>
    <field name="code"/>
    <field name="journal_id"/>
    <button name="%d" string="Save This Distribution as a Model" type="action" colspan="2"/>
    """% (tools.to_xml(plan_id.name), wiz_id[0])
                for line in plan_id.plan_ids:
                    res['arch']+="""
                    <field name="account%d_ids" string="%s" nolabel="1" colspan="4">
                    <tree string="%s" editable="bottom">
                        <field name="rate"/>
                        <field name="analytic_account_id" domain="[('parent_id','child_of',[%d])]" groups="base.group_extended"/>
                    </tree>
                </field>
                <newline/>"""%(i,tools.to_xml(line.name),tools.to_xml(line.name),line.root_analytic_id and line.root_analytic_id.id or 0)
                    i+=1
                res['arch'] += "</form>"
                doc = etree.fromstring(res['arch'].encode('utf8'))
                xarch, xfields = self._view_look_dom_arch(cr, uid, doc, view_id, context=context)
                res['arch'] = xarch
                res['fields'] = xfields
            return res
        else:
            return res
Example #17
0
    def wid_add(self, widget, colspan=1, name=None, expand=False, xoptions=False, ypadding=0, help=False, rowspan=1):
        self.count += 1
        (table, x, y) = self.cont[-1]
        if name:
            vbox = gtk.VBox(homogeneous=False, spacing=2)
            label = gtk.Label(name)
            label.set_alignment(0.0, 0.0)
            if help:
                try:
                    vbox.set_tooltip_markup(
                        '<span foreground="darkred"><b>' + tools.to_xml(name) + "</b></span>\n" + tools.to_xml(help)
                    )
                except:
                    pass
                label.set_markup('<sup><span foreground="darkgreen">?</span></sup>' + tools.to_xml(name))
            vbox.pack_start(label, expand=False)
            vbox.pack_start(widget, expand=expand, fill=False)
            wid = vbox
            wid.set_border_width(2)
        else:
            wid = widget
            if help:
                try:
                    wid.set_tooltip_markup('<span foreground="darkred"></span>' + tools.to_xml(help))
                except:
                    pass

        yopt = False
        if expand:
            yopt = yopt | gtk.EXPAND | gtk.FILL
        if not xoptions:
            xoptions = gtk.FILL | gtk.EXPAND
        table.attach(
            wid, x, x + colspan, y, y + rowspan, yoptions=yopt, xoptions=xoptions, ypadding=ypadding, xpadding=0
        )
        self.cont[-1] = (table, x + colspan, y)
        wid_list = table.get_children()
        wid_list.reverse()
        table.set_focus_chain(wid_list)
        return wid
Example #18
0
        def process_workcenter(wrk):
            workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id'])
            cost_cycle = wrk['cycle']*workcenter.costs_cycle
            cost_hour = wrk['hour']*workcenter.costs_hour
            total = cost_cycle + cost_hour
            xml = '<row>'
            xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>'
            xml += "<col/>"
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour + cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += '</row>'

            return xml, total
Example #19
0
        def process_workcenter(wrk):
            workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id'])
            cost_cycle = wrk['cycle']*workcenter.costs_cycle
            cost_hour = wrk['hour']*workcenter.costs_hour
            total = cost_cycle + cost_hour
            xml = '<row>'
            xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>'
            xml += "<col/>"
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour + cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += '</row>'

            return xml, total
Example #20
0
    def create(self, cr, uid, ids, datas, context):
        _divide_columns_for_matrix = 0.7
        _display_ans_in_rows = 5
        _pageSize = ('29.7cm', '21.1cm')
        if datas.has_key('form') and datas['form'].get('orientation',
                                                       '') == 'vertical':
            if datas['form'].get('paper_size', '') == 'letter':
                _pageSize = ('21.6cm', '27.9cm')
            elif datas['form'].get('paper_size', '') == 'legal':
                _pageSize = ('21.6cm', '35.6cm')
            elif datas['form'].get('paper_size', '') == 'a4':
                _pageSize = ('21.1cm', '29.7cm')
        elif datas.has_key('form') and datas['form'].get('orientation',
                                                         '') == 'horizontal':
            if datas['form'].get('paper_size', '') == 'letter':
                _pageSize = ('27.9cm', '21.6cm')
            elif datas['form'].get('paper_size', '') == 'legal':
                _pageSize = ('35.6cm', '21.6cm')
            elif datas['form'].get('paper_size', '') == 'a4':
                _pageSize = ('29.7cm', '21.1cm')

        _frame_width = tools.ustr(_pageSize[0])
        _frame_height = tools.ustr(
            float(_pageSize[1].replace('cm', '')) - float(1.90)) + 'cm'
        _tbl_widths = tools.ustr(
            float(_pageSize[0].replace('cm', '')) - float(2.10)) + 'cm'

        rml = """<document filename="Survey Form.pdf">
            <template pageSize="(""" + _pageSize[0] + """,""" + _pageSize[
            1] + """)" title='Survey Form' author="OpenERP S.A.([email protected])" allowSplitting="20" >
                <pageTemplate id="first">
                    <frame id="first" x1="0.0cm" y1="1.0cm" width='""" + _frame_width + """' height='""" + _frame_height + """'/>
                    <pageGraphics>
                        <lineMode width="1.0"/>
                        <lines>1.0cm """ + tools.ustr(
                float(_pageSize[1].replace('cm', '')) -
                float(1.00)) + 'cm' + """ """ + tools.ustr(
                    float(_pageSize[0].replace('cm', '')) -
                    float(1.00)) + 'cm' + """ """ + tools.ustr(
                        float(_pageSize[1].replace('cm', '')) -
                        float(1.00)) + 'cm' + """</lines>
                        <lines>1.0cm """ + tools.ustr(
                            float(_pageSize[1].replace('cm', '')) - float(1.00)
                        ) + 'cm' + """ 1.0cm 1.00cm</lines>
                        <lines>""" + tools.ustr(
                            float(_pageSize[0].replace('cm', '')) -
                            float(1.00)) + 'cm' + """ """ + tools.ustr(
                                float(_pageSize[1].replace('cm', '')) -
                                float(1.00)) + 'cm' + """ """ + tools.ustr(
                                    float(_pageSize[0].replace('cm', '')) -
                                    float(1.00)) + 'cm' + """ 1.00cm</lines>
                        <lines>1.0cm 1.00cm """ + tools.ustr(
                                        float(_pageSize[0].replace('cm', '')) -
                                        float(1.00)
                                    ) + 'cm' + """ 1.00cm</lines>"""

        if datas.has_key('form') and datas['form']['page_number']:
            rml += """
                    <fill color="gray"/>
                    <setFont name="Helvetica" size="10"/>
                    <drawRightString x='""" + tools.ustr(
                float(_pageSize[0].replace('cm', '')) - float(1.00)
            ) + 'cm' + """' y="0.6cm">Page : <pageNumber/> </drawRightString>"""
        rml += """</pageGraphics>
                </pageTemplate>
            </template>
            <stylesheet>
            <blockTableStyle id="ans_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="tbl_white">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="tbl_gainsboro">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
              <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="ans_tbl_white">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="ans_tbl_gainsboro">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="page_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
              <blockBackground colorName="gray" start="0,0" stop="-1,-1"/>
              <blockTextColor colorName="white" start="0,0" stop="0,0"/>
            </blockTableStyle>
            <blockTableStyle id="title_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
              <blockBackground colorName="black" start="0,0" stop="-1,-1"/>
              <blockTextColor colorName="white" start="0,0" stop="0,0"/>
            </blockTableStyle>
            <blockTableStyle id="question_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="note_table">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
            </blockTableStyle>
            <blockTableStyle id="tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <initialize>
              <paraStyle name="all" alignment="justify"/>
            </initialize>
            <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
            <paraStyle name="page" fontName="helvetica-bold" fontSize="15.0" leftIndent="0.0" textColor="white"/>
            <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
            <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
            <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="0.0"/>
            <paraStyle name="descriptive_text" fontName="helvetica" fontSize="10.0" leftIndent="0.0"/>
            <paraStyle name="answer_left" alignment="LEFT" fontName="helvetica-bold" fontSize="8.0" leftIndent="0.0"/>
            <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
            <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/>
            <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/>
            <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
            <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
        </stylesheet>
        <story>"""
        surv_obj = pooler.get_pool(cr.dbname).get('survey')
        for survey in surv_obj.browse(cr, uid, ids):
            rml += """
            <blockTable colWidths='""" + _tbl_widths + """' style="title_tbl">
                <tr><td><para style="title">""" + to_xml(
                tools.ustr(survey.title)
            ) + """</para><para style="P2"><font></font></para></td></tr>
            </blockTable>"""
            if survey.note:
                rml += """
                <para style="P2"></para>
                    <blockTable colWidths='""" + _tbl_widths + """' style="note_table">
                        <tr><td><para style="descriptive_text">""" + to_xml(
                    tools.ustr(survey.note)
                ) + """</para><para style="P2"><font></font></para></td></tr>
                    </blockTable>"""

            seq = 0
            for page in survey.page_ids:
                seq += 1
                rml += """
                <blockTable colWidths='""" + _tbl_widths + """' style="page_tbl">
                    <tr><td><para style="page">""" + tools.ustr(
                    seq) + """. """ + to_xml(tools.ustr(
                        page.title)) + """</para></td></tr>
                </blockTable>"""
                if page.note:
                    rml += """<para style="P2"></para><blockTable colWidths='""" + _tbl_widths + """' style="note_table">
                                <tr><td><para style="descriptive_text">""" + to_xml(
                        tools.ustr(page.note or '')) + """</para></td></tr>
                            </blockTable>"""

                for que in page.question_ids:
                    cols_widhts = []
                    rml += """
                    <para style="P2"><font></font></para>
                    <blockTable colWidths='""" + _tbl_widths + """' style="question_tbl">
                        <tr><td><para style="question">""" + to_xml(
                        tools.ustr(que.question)) + """</para></td></tr>
                    </blockTable>
                    <para style="P2"><font></font></para>"""
                    if que.type in ['descriptive_text']:
                        cols_widhts.append(float(_tbl_widths.replace('cm',
                                                                     '')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths + 'cm'
                        rml += """
                        <blockTable colWidths=" """ + colWidths + """ " style="ans_tbl">
                            <tr>
                                <td>
                                <para style="descriptive_text">""" + to_xml(
                            tools.ustr(que.descriptive_text)) + """</para>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in [
                            'multiple_choice_multiple_ans',
                            'multiple_choice_only_one_ans'
                    ]:
                        answer = []
                        for ans in que.answer_choice_ids:
                            answer.append(to_xml(tools.ustr((ans.answer))))

                        def divide_list(lst, n):
                            return [lst[i::n] for i in range(n)]

                        divide_list = divide_list(answer, _display_ans_in_rows)
                        for lst in divide_list:
                            if que.type == 'multiple_choice_multiple_ans':
                                if len(lst) <> 0 and len(lst) <> int(
                                        round(
                                            float(len(answer)) /
                                            _display_ans_in_rows, 0)):
                                    lst.append('')
                            if not lst:
                                del divide_list[divide_list.index(lst):]
                        for divide in divide_list:
                            a = _divide_columns_for_matrix * len(divide)
                            b = float(_tbl_widths.replace('cm', '')) - float(a)
                            cols_widhts = []

                            for div in range(0, len(divide)):
                                cols_widhts.append(float(a / len(divide)))
                                cols_widhts.append(float(b / len(divide)))
                            colWidths = "cm,".join(map(tools.ustr,
                                                       cols_widhts))
                            colWidths = colWidths + 'cm'
                            rml += """<blockTable colWidths=" """ + colWidths + """ " style="ans_tbl">
                                        <tr>"""
                            for div in range(0, len(divide)):
                                if divide[div] != '':
                                    if que.type == 'multiple_choice_multiple_ans':
                                        rml += """
                                           <td>
                                               <illustration>
                                                   <rect x="0.1cm" y="-0.4cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes"/>
                                                </illustration>
                                           </td>
                                           <td><para style="answer">""" + divide[
                                            div] + """</para></td>"""
                                    else:
                                        rml += """
                                       <td>
                                           <illustration>
                                               <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes"/>
                                            </illustration>
                                       </td>
                                       <td><para style="answer">""" + divide[
                                            div] + """</para></td>"""
                                else:
                                    rml += """
                                   <td></td>
                                   <td></td>"""
                            rml += """
                            </tr></blockTable>"""

                    elif que.type in [
                            'matrix_of_choices_only_one_ans', 'rating_scale',
                            'matrix_of_choices_only_multi_ans',
                            'matrix_of_drop_down_menus'
                    ]:
                        if len(que.column_heading_ids):
                            cols_widhts.append(
                                float(_tbl_widths.replace('cm', '')) /
                                float(2.0))
                            for col in que.column_heading_ids:
                                cols_widhts.append(
                                    float(
                                        (float(_tbl_widths.replace('cm', '')) /
                                         float(2.0)) /
                                        len(que.column_heading_ids)))
                        else:
                            cols_widhts.append(
                                float(_tbl_widths.replace('cm', '')))

                        tmp = 0.0
                        sum = 0.0
                        i = 0
                        if que.comment_column:
                            for col in cols_widhts:
                                if i == 0:
                                    cols_widhts[i] = cols_widhts[i] / 2.0
                                    tmp = cols_widhts[i]
                                sum += col
                                i += 1
                            cols_widhts.append(round(tmp, 2))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths + 'cm'
                        matrix_ans = [
                            '',
                        ]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append(col.title)
                        if que.comment_column:
                            matrix_ans.append(
                                to_xml(tools.ustr(que.column_name)))
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="ans_tbl"><tr>"""

                        for mat_col in matrix_ans:
                            rml += """<td><para style="response">""" + to_xml(
                                tools.ustr(mat_col)) + """</para></td>"""
                        rml += """</tr></blockTable>"""
                        i = 0
                        for ans in que.answer_choice_ids:
                            if i % 2 != 0:
                                style = 'ans_tbl_white'
                            else:
                                style = 'ans_tbl_gainsboro'
                            i += 1
                            rml += """
                            <blockTable colWidths=" """ + colWidths + """ " style='""" + style + """'>
                            <tr><td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)) + """</para></td>"""
                            rec_width = float((sum - tmp) * 10 + 100)
                            value = ""

                            if que.type in ['matrix_of_drop_down_menus']:
                                value = """ <fill color="white"/>
                                    <rect x="-0.1cm" y="-0.45cm" width='""" + tools.ustr(
                                    cols_widhts[-1] - 0.5
                                ) + "cm" + """' height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/>"""
                            elif que.type in [
                                    'matrix_of_choices_only_one_ans',
                                    'rating_scale'
                            ]:
                                value = """ <fill color="white"/>
                                    <circle x="0.35cm" y="-0.18cm" radius="0.25 cm" fill="yes" stroke="yes"/>"""
                            else:
                                value = """ <fill color="white"/>
                                    <rect x="0.1cm" y="-0.4cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/>"""
                            for mat_col in range(1, len(matrix_ans)):
                                if matrix_ans[mat_col] == que.column_name:
                                    if mat_col == 1:
                                        rml += """
                                            <td><para style="answer_left">""" + to_xml(
                                            tools.ustr(que.column_name)
                                        ) + """</para></td>"""
                                    else:
                                        rml += """<td></td>"""
                                else:
                                    rml += """<td><illustration>""" + value + """</illustration></td>"""
                            rml += """</tr></blockTable>"""

                    elif que.type in [
                            'multiple_textboxes', 'numerical_textboxes',
                            'date_and_time', 'date',
                            'multiple_textboxes_diff_type'
                    ]:
                        cols_widhts.append(
                            float(_tbl_widths.replace('cm', '')) / 2)
                        cols_widhts.append(
                            float(_tbl_widths.replace('cm', '')) / 2)
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = tools.ustr(colWidths) + 'cm'
                        for ans in que.answer_choice_ids:
                            rml += """<para style="P1"></para>
                            <blockTable colWidths=" """ + colWidths + """ " style="ans_tbl">
                                <tr>
                                <td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)
                            ) + """</para></td>
                                    <td>
                                    <illustration>
                                        <rect x="0.0cm" y="-0.5cm" width='""" + tools.ustr(
                                str(cols_widhts[0] - 0.3) + "cm"
                            ) + """' height="0.6cm" fill="no" stroke="yes"/>
                                    </illustration>
                                    </td>
                                </tr>
                            </blockTable>"""

                    elif que.type in ['comment']:
                        cols_widhts.append(float(_tbl_widths.replace('cm',
                                                                     '')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        rml += """<blockTable colWidths=" """ + colWidths + """cm " style="ans_tbl">
                            <tr>
                                <td><para style="comment"><font color="white"> </font></para>
                                    <illustration>
                                        <rect x="0.1cm" y="0.3cm" width='""" + tools.ustr(
                            str(float(colWidths) - 0.6) + 'cm'
                        ) + """' height="1.5cm" fill="no" stroke="yes"/>
                                    </illustration>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in ['single_textbox']:
                        cols_widhts.append(float(_tbl_widths.replace('cm',
                                                                     '')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        rml += """<para style="P2"><font color="white"> </font></para>
                        <blockTable colWidths=" """ + colWidths + """cm " style="ans_tbl">
                            <tr>
                                <td>
                                    <illustration>
                                        <rect x="0.2cm" y="0.3cm" width='""" + tools.ustr(
                            str(float(colWidths) - 0.7) + 'cm'
                        ) + """' height="0.6cm" fill="no" stroke="yes"/>
                                    </illustration>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in ['table']:
                        tbl_width = float(_tbl_widths.replace('cm', ''))
                        for i in range(0, len(que.column_heading_ids)):
                            cols_widhts.append(
                                tbl_width / float(len(que.column_heading_ids)))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths + 'cm'
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="tbl"><tr>"""
                        for col in que.column_heading_ids:
                            rml += """<td><para style="terp_tblheader_Details">""" + to_xml(
                                tools.ustr(col.title)) + """</para></td>"""
                        rml += """</tr></blockTable>"""
                        i = 0
                        for r in range(0, que.no_of_rows):
                            if i % 2 != 0:
                                style = 'tbl_white'
                            else:
                                style = 'tbl_gainsboro'
                            i += 1
                            rml += """<blockTable colWidths=" """ + colWidths + """ " style='""" + style + """'><tr>"""
                            for c in que.column_heading_ids:
                                rml += """
                                <td><para style="terp_default_9"><font color="white"> </font></para></td>"""
                            rml += """</tr></blockTable>"""

            if datas.has_key(
                    'form') and not datas['form']['without_pagebreak']:
                rml += """<pageBreak/>"""
            elif not datas.has_key('form'):
                rml += """<pageBreak/>"""
            else:
                rml += """<para style="P2"><font></font></para>"""

        rml += """</story></document>"""
        report_type = datas.get('report_type', 'pdf')
        create_doc = self.generators[report_type]
        pdf = create_doc(rml, title=self.title)
        return (pdf, report_type)
Example #21
0
    def create_xml(self, cr, uid, ids, data, context=None):
        partner_id = ids[0]

        pool = pooler.get_pool(cr.dbname)
        user_pool = pool.get('res.users')
        company_id = user_pool.browse(cr, uid, uid).company_id

        period_from_id = data['form']['period_from_id']
        period_to_id = data['form']['period_to_id']
        pool_period = pool.get('account.period')
        period_from = pool_period.browse(cr, uid, period_from_id)
        period_to = pool_period.browse(cr, uid, period_to_id)

        pool_partner = pool.get('res.partner')
        partner = pool_partner.browse(cr, uid, partner_id)

        date_from = period_from['date_start']
        date_to = period_to['date_stop']
        rml_obj = report_sxw.rml_parse(cr, uid, pool_period._name, context)
        rml_obj.localcontext.update({'lang': context.get('lang', False)})
        if date_from > date_to:
            raise osv.except_osv(
                _('Error'),
                _('Start period should be smaller than end period'))

        sql = '''
            select per.name as period_name, per.date_start as period_start, per.date_stop as period_stop,
            sum(inv.amount_untaxed) as total_untaxed, sum(inv.amount_total) as total
            from account_invoice inv inner join account_period per on inv.period_id = per.id
            where inv.partner_id = %s
            and per.date_start >= date(%s)
            and per.date_stop <= date(%s)
            and inv.state in ('open', 'paid')
            group by per.name, per.date_start, per.date_stop
            order by per.date_start
            '''

        cr.execute(sql, (partner_id, date_from, date_to))

        results = cr.dictfetchall()
        if not results:
            raise osv.except_osv(_('No Data Available'),
                                 _('No records found for your selection!'))

        xml = ''
        config_start = """
        <config>
            <date>Data: """ + to_xml(
            rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d'),
                               date=True)) + """</date>
            <reportname>STAMPA CLIENTI/FORNITORI</reportname>
            <company>Azienda: %s</company>
            <PageSize>210.00mm,297.00mm</PageSize>
            <PageWidth>595.27</PageWidth>
            <PageHeight>841.88</PageHeight>
            <tableSize>60.00mm,80.00mm,40.00mm</tableSize>
            """ % (company_id.name)
        config_stop = """
            <report-footer>Generated by OpenERP</report-footer>
        </config>
        """

        partner_type = ''
        if partner.customer:
            partner_type += 'Cliente'
        if partner.customer and partner.supplier:
            partner_type += '/'
        if partner.supplier:
            partner_type += 'Fornitore'

        partner_ref = partner.ref or ''
        partner_name = partner.name
        partner_piva = partner.vat or ''

        title = """
                <row>
                    <col>""" + to_xml(partner_type) + """: """ + to_xml(
            partner_ref) + """</col>
                    <col>Rag. Soc.: """ + to_xml(partner_name) + """</col>
                    <col>P.IVA: """ + to_xml(partner_piva) + """</col>
                </row>"""

        invoice_header = """
                <row>
                    <col>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>""" % (_('Periodo'), _('Fatturato'), _('Fatt. Netto'))

        xml += "<lines style='total'>" + title + "</lines>" + "<lines style='header'>" + invoice_header + "</lines>"

        purchase_price_digits = rml_obj.get_digits(dp='Purchase Price')

        company_currency = company_id.currency_id
        company_currency_symbol = company_currency.symbol or company_currency.name

        for period in results:
            period_name = period['period_name']
            total_untaxed = period['total_untaxed']
            total = period['total']
            xml += """<lines style='lines'><row>
                <col para='yes'>""" + period_name + """</col>
                <col f='yes'>""" + rml_obj.formatLang(
                total, digits=purchase_price_digits) + ' ' + (
                    company_currency_symbol) + """</col>
                <col f='yes'>""" + rml_obj.formatLang(
                        total_untaxed, digits=purchase_price_digits) + ' ' + (
                            company_currency_symbol) + """</col>
                </row></lines>"""

        xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>'

        return xml
    def create(self, cr, uid, ids, datas, context):
        _divide_columns_for_matrix = 0.7
        _display_ans_in_rows = 5
        _pageSize = ('29.7cm','21.1cm')

        if datas.has_key('form') and datas['form'].get('orientation','') == 'vertical':
            if datas['form'].get('paper_size','') == 'letter':
                _pageSize = ('21.6cm','27.9cm')
            elif datas['form'].get('paper_size','') == 'legal':
                _pageSize = ('21.6cm','35.6cm')
            elif datas['form'].get('paper_size','') == 'a4':
                _pageSize = ('21.1cm','29.7cm')

        elif datas.has_key('form') and datas['form'].get('orientation',False) == 'horizontal':
            if datas['form'].get('paper_size','') == 'letter':
                _pageSize = ('27.9cm','21.6cm')
            elif datas['form'].get('paper_size','') == 'legal':
                _pageSize = ('35.6cm','21.6cm')
            elif datas['form'].get('paper_size') == 'a4':
                _pageSize = ('29.7cm','21.1cm')

        _frame_width = tools.ustr(_pageSize[0])
        _frame_height = tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.90))+'cm'
        _tbl_widths = tools.ustr(float(_pageSize[0].replace('cm','')) - float(2.10))+'cm'
        rml ="""<document filename="Survey Answer Report.pdf">
                <template pageSize="("""+_pageSize[0]+""","""+_pageSize[1]+""")" title='Survey Answer' author="OpenERP S.A.([email protected])" allowSplitting="20" >
                    <pageTemplate id="first">
                        <frame id="first" x1="0.0cm" y1="1.0cm" width='"""+_frame_width+"""' height='"""+_frame_height+"""'/>
                        <pageGraphics>
                            <lineMode width="1.0"/>
                            <lines>1.0cm """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+"""</lines>
                            <lines>1.0cm """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" 1.0cm 1.00cm</lines>
                            <lines>"""+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" 1.00cm</lines>
                            <lines>1.0cm 1.00cm """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" 1.00cm</lines>"""
        if datas.has_key('form') and datas['form']['page_number']:
            rml +="""
                    <fill color="gray"/>
                    <setFont name="Helvetica" size="10"/>
                    <drawRightString x='"""+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+"""' y="0.6cm">Page : <pageNumber/> </drawRightString>"""
        rml +="""</pageGraphics>
                    </pageTemplate>
                </template>
                  <stylesheet>
                    <blockTableStyle id="tbl_white">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="tbl_gainsboro">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="ans_tbl_white">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="ans_tbl_gainsboro">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="simple_table">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/>
                    </blockTableStyle>
                    <blockTableStyle id="note_table">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table3">
                      <blockAlignment value="LEFT"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table4">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table5">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table41">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table51">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_heading">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="title_tbl">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                      <blockBackground colorName="black" start="0,0" stop="-1,-1"/>
                      <blockTextColor colorName="white" start="0,0" stop="0,0"/>
                    </blockTableStyle>
                    <blockTableStyle id="page_tbl">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                      <blockBackground colorName="gray" start="0,0" stop="-1,-1"/>
                      <blockTextColor colorName="white" start="0,0" stop="0,0"/>
                    </blockTableStyle>
                    <initialize>
                      <paraStyle name="all" alignment="justify"/>
                    </initialize>
                    <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
                    <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/>
                    <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/>
                    <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/>
                    <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
                    <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/>
                    <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
                    <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer1" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/>
                    <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/>
                    <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_default_9_Bold" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_tblheader_General_Centre_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_right_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_right" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="descriptive_text" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
                    <paraStyle name="descriptive_text_heading" fontName="helvetica-bold" fontSize="18.0" alignment="RIGHT" leftIndent="0.0" textColor="white"/>
                  </stylesheet>
                  <images/>
                  <story>"""
        surv_resp_obj = pooler.get_pool(cr.dbname).get('survey.response')
        rml_obj=report_sxw.rml_parse(cr, uid, surv_resp_obj._name,context)
        if datas.has_key('form') and datas['form'].has_key('response_ids'):
            response_id = datas['form']['response_ids']
        elif context.has_key('response_id') and context['response_id']:
            response_id = [int(context['response_id'][0])]
        else:
            response_id = surv_resp_obj.search(cr, uid, [('survey_id', 'in', ids)])

        surv_resp_line_obj = pooler.get_pool(cr.dbname).get('survey.response.line')
        surv_obj = pooler.get_pool(cr.dbname).get('survey')

        for response in surv_resp_obj.browse(cr, uid, response_id):
            for survey in surv_obj.browse(cr, uid, [response.survey_id.id]):
                tbl_width = float(_tbl_widths.replace('cm', ''))
                colwidth =  "2.5cm,4.8cm," + str(tbl_width - 15.0) +"cm,3.2cm,4.5cm"
                resp_create = tools.ustr(time.strftime('%d-%m-%Y %I:%M:%S %p', time.strptime(response.date_create.split('.')[0], '%Y-%m-%d %H:%M:%S')))
                rml += """<blockTable colWidths='""" + colwidth + """' style="Table_heading">
                          <tr>
                            <td><para style="terp_default_9_Bold">Print Date : </para></td>
                            <td><para style="terp_default_9">""" + to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),date_time=True)) + """</para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9_Bold">Answered by : </para></td>
                            <td><para style="terp_default_9">""" + to_xml(response.user_id.login or '') + """</para></td>
                          </tr>
                          <tr>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9_Bold">Answer Date : </para></td>
                            <td><para style="terp_default_9">""" + to_xml(resp_create) +  """</para></td>
                          </tr>
                        </blockTable><para style="P2"></para>"""

                status = "Not Finished"
                if response.state == "done": status = "Finished"
                colwidth =  str(tbl_width - 7) + "cm,"
                colwidth +=  "7cm"
                rml += """<blockTable colWidths='""" + str(colwidth) + """' style="title_tbl">
                            <tr>
                            <td><para style="title">""" + to_xml(tools.ustr(survey.title)) + """</para><para style="P2"><font></font></para></td>
                            <td><para style="descriptive_text_heading">Status :- """ + to_xml(tools.ustr(status)) + """</para><para style="P2"><font></font></para></td>
                            </tr>
                        </blockTable>"""

                if survey.note:
                    rml += """<blockTable colWidths='""" + _tbl_widths + """' style="note_table">
                            <tr><td><para style="response">""" + to_xml(tools.ustr(survey.note or '')) + """</para><para style="P2"><font></font></para></td></tr>
                        </blockTable>"""

                for page in survey.page_ids:
                    rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="page_tbl">
                                  <tr><td><para style="page">Page :- """ + to_xml(tools.ustr(page.title or '')) + """</para></td></tr>
                              </blockTable>"""
                    if page.note:
                        rml += """<para style="P2"></para>
                                 <blockTable colWidths='""" + str(_tbl_widths) + """' style="note_table">
                                      <tr><td><para style="response">""" + to_xml(tools.ustr(page.note or '')) + """</para></td></tr>
                                 </blockTable>"""

                    for que in page.question_ids:
                        rml += """<para style="P2"></para>
                                <blockTable colWidths='""" + str(_tbl_widths) + """' style="Table5">
                                  <tr><td><para style="question">""" + to_xml(to_xml(que.question)) + """</para></td></tr>
                                </blockTable>"""

                        answer = surv_resp_line_obj.browse(cr ,uid, surv_resp_line_obj.search(cr, uid, [('question_id', '=', que.id),('response_id', '=', response.id)]))
                        if que.type in ['descriptive_text']:
                            rml +="""<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr><td> <para style="response">""" + to_xml(tools.ustr(que.descriptive_text)) + """</para></td> </tr>
                                    </blockTable>"""

                        elif que.type in ['table']:
                            if len(answer) and answer[0].state == "done":
                                col_heading = pooler.get_pool(cr.dbname).get('survey.tbl.column.heading')
                                cols_widhts = []
                                tbl_width = float(_tbl_widths.replace('cm', ''))
                                for i in range(0, len(que.column_heading_ids)):
                                    cols_widhts.append(tbl_width / float(len(que.column_heading_ids)))
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = colWidths + 'cm'
                                matrix_ans = []
                                rml +="""<para style="P2"></para><blockTable colWidths=" """ + str(colWidths) + """ " style="Table41"><tr>"""

                                for col in que.column_heading_ids:
                                    if col.title not in matrix_ans:
                                        matrix_ans.append(col.title)
                                        rml += """<td> <para style="terp_tblheader_Details">""" + to_xml(tools.ustr(col.title)) +"""</para></td>"""
                                rml += """</tr></blockTable>"""
                                i = 0

                                for row in range(0, que.no_of_rows):
                                    if i%2 != 0:
                                        style = 'tbl_white'
                                    else:
                                        style = 'tbl_gainsboro'
                                    i +=1
                                    rml += """<blockTable colWidths=" """ + str(colWidths) + """ " style='"""+style+"""'><tr>"""
                                    table_data = col_heading.browse(cr, uid, col_heading.search(cr, uid, [('response_table_id', '=', answer[0].id), ('name', '=', row)]))
                                    for column in matrix_ans:
                                        value = False
                                        for col in table_data:
                                            if column == col.column_id.title:
                                                value = col.value
                                        if value:
                                            rml += """<td> <para style="terp_default_9">""" + to_xml(tools.ustr(value)) +"""</para></td>"""
                                        else:
                                            rml += """<td><para style="terp_default_9"><font color ="white"> </font></para></td>"""
                                    rml += """</tr></blockTable>"""

                            else:
                                rml +="""<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                             <tr><td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""

                        elif que.type in ['multiple_choice_only_one_ans','multiple_choice_multiple_ans']:
                            if len(answer) and answer[0].state == "done":
                                ans_list = []
                                for ans in answer[0].response_answer_ids:
                                    ans_list.append(to_xml(tools.ustr(ans.answer_id.answer)))
                                answer_choice=[]

                                for ans in que['answer_choice_ids']:
                                    answer_choice.append(to_xml(tools.ustr((ans.answer))))

                                def divide_list(lst, n):
                                    return [lst[i::n] for i in range(n)]

                                divide_list = divide_list(answer_choice,_display_ans_in_rows)
                                for lst in divide_list:
                                    if que.type == 'multiple_choice_multiple_ans':
                                        if len(lst) <> 0 and len(lst) <> int(round(float(len(answer_choice)) / _display_ans_in_rows, 0)):
                                           lst.append('')
                                    if not lst:
                                       del divide_list[divide_list.index(lst):]

                                for divide in divide_list:
                                    a = _divide_columns_for_matrix * len(divide)
                                    b = float(_tbl_widths.replace('cm', '')) - float(a)
                                    cols_widhts = []
                                    for div in range(0, len(divide)):
                                        cols_widhts.append(float(a / len(divide)))
                                        cols_widhts.append(float(b / len(divide)))
                                    colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                    colWidths = colWidths +'cm'
                                    rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>"""

                                    for div in range(0, len(divide)):
                                       if divide[div] != '':
                                           if que.type == 'multiple_choice_multiple_ans':
                                               if divide[div] in ans_list:
                                                   rml += """<td><illustration><fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                <fill color="gray"/>
                                                                <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>
                                                                </illustration></td>
                                                             <td><para style="answer">""" + divide[div] + """</para></td>"""
                                               else:
                                                   rml+="""<td><illustration>
                                                           <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes"  round="0.1cm"/>
                                                            </illustration></td>
                                                           <td><para style="answer">""" + divide[div] + """</para></td>"""
                                           else:
                                               if divide[div] in ans_list:
                                                   rml += """<td><illustration><fill color="white"/>
                                                            <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/>
                                                            <fill color="gray"/>
                                                            <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no" round="0.1cm"/>
                                                        </illustration></td>
                                                   <td><para style="answer">""" + divide[div] + """</para></td>"""
                                               else:
                                                   rml += """<td>
                                                               <illustration>
                                                                   <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes" round="0.1cm"/>
                                                                </illustration>
                                                           </td>
                                                           <td><para style="answer">""" + divide[div] + """</para></td>"""
                                       else:
                                           rml += """<td></td><td></td>"""
                                    rml += """</tr></blockTable>"""

                                if que.is_comment_require and answer[0].comment:
                                    rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"><tr>
                                                <td><para style="answer">""" + to_xml(tools.ustr(answer[0].comment)) + """</para></td></tr></blockTable>"""
                            else:
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                             <tr><td> <para style="response">No Answer</para></td> </tr>
                                          </blockTable>"""

                        elif que.type in ['multiple_textboxes_diff_type','multiple_textboxes','date','date_and_time','numerical_textboxes','multiple_textboxes_diff_type']:
                            if len(answer) and answer[0].state == "done":
                                cols_widhts = []
                                cols_widhts.append(float(_tbl_widths.replace('cm',''))/2)
                                cols_widhts.append(float(_tbl_widths.replace('cm',''))/2)
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = tools.ustr(colWidths) + 'cm'
                                answer_list = {}

                                for ans in answer[0].response_answer_ids:
                                    answer_list[ans.answer_id.answer] = ans.answer
                                for que_ans in que['answer_choice_ids']:
                                    if que_ans.answer in answer_list:
                                        rml += """<blockTable colWidths='""" + str(colWidths) + """' style="simple_table">
                                                 <tr> <td> <para style="response">""" + to_xml(tools.ustr(que_ans.answer)) + """</para></td>
                                                 <td> <para style="response">""" + to_xml(tools.ustr(answer_list[que_ans.answer])) + """</para></td></tr>
                                                </blockTable>"""
                                    else:
                                        rml += """<blockTable colWidths='""" + str(colWidths) + """' style="simple_table">
                                                 <tr> <td> <para style="response">""" + to_xml(tools.ustr(que_ans.answer)) + """</para></td>
                                                 <td> <para style="response"></para></td></tr>
                                                </blockTable>"""
                            else:
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""

                        elif que.type in ['single_textbox']:
                            if len(answer) and answer[0].state == "done":
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr> <td> <para style="response">""" + to_xml(tools.ustr(answer[0].single_text)) + """</para></td></tr>
                                        </blockTable>"""
                            else:
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""

                        elif que.type in ['comment']:
                            if len(answer) and answer[0].state == "done":
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr> <td> <para style="response">""" + to_xml(tools.ustr(answer[0].comment)) + """</para></td></tr>
                                        </blockTable>"""
                            else:
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""

                        elif que.type in ['matrix_of_choices_only_one_ans','matrix_of_choices_only_multi_ans', 'rating_scale', 'matrix_of_drop_down_menus']:
                            if len(answer) and answer[0].state == "done":
                                if que.type  in ['matrix_of_choices_only_one_ans', 'rating_scale'] and que.comment_column:
                                    pass
                                cols_widhts = []
                                if len(que.column_heading_ids):
                                    cols_widhts.append(float(_tbl_widths.replace('cm','')) / float(2.0))
                                    for col in que.column_heading_ids:
                                        cols_widhts.append(float((float(_tbl_widths.replace('cm','')) / float(2.0)) / len(que.column_heading_ids)))
                                else:
                                    cols_widhts.append(float(_tbl_widths.replace('cm','')))

                                tmp = 0.0
                                sum =  0.0
                                i = 0
                                if que.type in ['matrix_of_choices_only_one_ans','rating_scale'] and que.comment_column:
                                    for col in cols_widhts:
                                        if i == 0:
                                            cols_widhts[i] = cols_widhts[i] / 2.0
                                            tmp = cols_widhts[i]
                                        sum += col
                                        i += 1
                                    cols_widhts.append(round(tmp, 2))
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = colWidths + 'cm'
                                matrix_ans = [(0, ''),]

                                for col in que.column_heading_ids:
                                    if col.title not in matrix_ans:
                                        matrix_ans.append((col.id, col.title))
                                len_matrix = len(matrix_ans)
                                if que.type in ['matrix_of_choices_only_one_ans', 'rating_scale'] and que.comment_column:
                                    matrix_ans.append((0,que.column_name))
                                rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>"""

                                for mat_col in range(0, len(matrix_ans)):
                                    rml += """<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>"""
                                rml += """</tr>"""
                                rml += """</blockTable>"""
                                i = 0

                                for ans in que.answer_choice_ids:
                                    if i%2 != 0:
                                        style = 'ans_tbl_white'
                                    else:
                                        style = 'ans_tbl_gainsboro'
                                    i += 1
                                    rml += """<blockTable colWidths=" """ + colWidths + """ " style='"""+style+"""'>
                                            <tr><td><para style="response">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>"""
                                    comment_value = ""
                                    for mat_col in range(1, len_matrix):
                                        value = """"""
                                        for res_ans in answer[0].response_answer_ids:
                                            if res_ans.answer_id.id == ans.id and res_ans.column_id.id == matrix_ans[mat_col][0]:
                                                comment_value = to_xml(tools.ustr(res_ans.comment_field))
                                                if que.type in ['matrix_of_drop_down_menus']:
                                                    value = """<para style="response">""" + to_xml(tools.ustr(res_ans.value_choice)) + """</para>"""
                                                elif que.type in ['matrix_of_choices_only_one_ans', 'rating_scale']:
                                                    value = """<illustration><fill color="white"/>
                                                                <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"/>
                                                                <fill color="gray"/>
                                                                <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no"/>
                                                            </illustration>"""
                                                elif que.type in ['matrix_of_choices_only_multi_ans']:
                                                    value = """<illustration>
                                                                <fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                <fill color="gray"/>
                                                                <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>
                                                                </illustration>"""
                                                break
                                            else:
                                                if que.type in ['matrix_of_drop_down_menus']:
                                                    value = """"""
                                                elif que.type in ['matrix_of_choices_only_one_ans','rating_scale']:
                                                    value = """<illustration><fill color="white"/>
                                                                    <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                </illustration>"""
                                                elif que.type in ['matrix_of_choices_only_multi_ans']:
                                                    value = """<illustration><fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                </illustration>"""
                                        rml+= """<td>""" + value + """</td>"""
                                    if que.type in ['matrix_of_choices_only_one_ans','rating_scale'] and que.comment_column:
                                        if comment_value == 'False':
                                            comment_value = ''
                                        rml += """<td><para style="response">""" + to_xml(tools.ustr(comment_value)) + """</para></td>"""
                                    rml += """</tr></blockTable>"""

                                if que.is_comment_require:
                                    rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"><tr>
                                            <td><para style="answer">""" + to_xml(tools.ustr(answer[0].comment or '')) + """</para></td></tr></blockTable>"""
                            else:
                                rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table">
                                         <tr><td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""

                if datas.has_key('form') and not datas['form']['without_pagebreak']:
                    rml += """<pageBreak/>"""
                elif not datas.has_key('form'):
                    rml += """<pageBreak/>"""
                else:
                    rml += """<para style="P2"><font></font></para>"""

        rml += """</story></document>"""
        report_type = datas.get('report_type', 'pdf')
        create_doc = self.generators[report_type]
        pdf = create_doc(rml, title=self.title)
        return (pdf, report_type)
Example #23
0
    def create_xml(self, cr, uid, ids, data, context=None):
        partner_id = ids[0]
       
        pool = pooler.get_pool(cr.dbname)
        user_pool = pool.get('res.users')
        company_id = user_pool.browse(cr, uid, uid).company_id
        
        period_from_id = data['form']['period_from_id']
        period_to_id = data['form']['period_to_id']
        pool_period = pool.get('account.period')
        period_from = pool_period.browse(cr, uid, period_from_id)
        period_to = pool_period.browse(cr, uid, period_to_id)
        
        pool_partner = pool.get('res.partner')
        partner = pool_partner.browse(cr, uid, partner_id)
        
        date_from = period_from['date_start']
        date_to = period_to['date_stop']
        rml_obj=report_sxw.rml_parse(cr, uid, pool_period._name,context)
        rml_obj.localcontext.update({'lang':context.get('lang',False)})
        if date_from > date_to:
            raise osv.except_osv(_('Error'), _('Start period should be smaller than end period'))
        
        sql = '''
            select per.name as period_name, per.date_start as period_start, per.date_stop as period_stop,
            sum(inv.amount_untaxed) as total_untaxed, sum(inv.amount_total) as total
            from account_invoice inv inner join account_period per on inv.period_id = per.id
            where inv.partner_id = %s
            and per.date_start >= date(%s)
            and per.date_stop <= date(%s)
            and inv.state in ('open', 'paid')
            group by per.name, per.date_start, per.date_stop
            order by per.date_start
            '''
               
        cr.execute(sql, (partner_id, date_from, date_to))
        
        results = cr.dictfetchall()
        if not results:
            raise osv.except_osv(_('No Data Available'), _('No records found for your selection!'))
        
        xml = ''
        config_start = """
        <config>
            <date>Data: """ + to_xml(rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d'),date=True)) + """</date>
            <reportname>STAMPA CLIENTI/FORNITORI</reportname>
            <company>Azienda: %s</company>
            <PageSize>210.00mm,297.00mm</PageSize>
            <PageWidth>595.27</PageWidth>
            <PageHeight>841.88</PageHeight>
            <tableSize>60.00mm,80.00mm,40.00mm</tableSize>
            """ % (company_id.name)
        config_stop = """
            <report-footer>Generated by OpenERP</report-footer>
        </config>
        """
        
        partner_type =''
        if partner.customer:
            partner_type +='Cliente'
        if partner.customer and partner.supplier:
            partner_type +='/'
        if partner.supplier:
            partner_type +='Fornitore'

        partner_ref = partner.ref or ''
        partner_name = partner.name
        partner_piva = partner.vat or ''
        
        title = """
                <row>
                    <col>""" + to_xml(partner_type) +""": """ + to_xml(partner_ref) + """</col>
                    <col>Rag. Soc.: """ + to_xml(partner_name) + """</col>
                    <col>P.IVA: """ + to_xml(partner_piva) + """</col>
                </row>"""
        
        invoice_header = """
                <row>
                    <col>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>""" % (_('Periodo'),_('Fatturato'), _('Fatt. Netto'))
                     
        xml += "<lines style='total'>" + title + "</lines>" + "<lines style='header'>" + invoice_header + "</lines>"
        
        purchase_price_digits = rml_obj.get_digits(dp='Purchase Price')
        
        company_currency = company_id.currency_id
        company_currency_symbol = company_currency.symbol or company_currency.name
        
        for period in results:
            period_name = period['period_name']
            total_untaxed = period['total_untaxed'] 
            total = period['total']
            xml += """<lines style='lines'><row>
                <col para='yes'>""" + period_name + """</col>
                <col f='yes'>""" + rml_obj.formatLang(total, digits=purchase_price_digits) + ' '+ (company_currency_symbol)  + """</col>
                <col f='yes'>""" + rml_obj.formatLang(total_untaxed, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col>
                </row></lines>"""

        xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>'

        return xml
Example #24
0
    def wid_add(self,
                widget,
                name=None,
                expand=False,
                ypadding=2,
                rowspan=1,
                colspan=1,
                translate=False,
                fname=None,
                help=False,
                fill=False,
                invisible=False):
        (table, x, y) = self.cont[-1]
        if colspan > self.col[-1]:
            colspan = self.col[-1]
        a = name and 1 or 0
        if colspan + x + a > self.col[-1]:
            self.newline()
            (table, x, y) = self.cont[-1]
        yopt = False
        if expand:
            yopt = yopt | gtk.EXPAND
        if fill:
            yopt = yopt | gtk.FILL
        if colspan == 1 and a == 1:
            colspan = 2
        if name:
            label = gtk.Label(name)
            eb = gtk.EventBox()
            eb.set_events(gtk.gdk.BUTTON_PRESS_MASK)
            self.trans_box_label.append((eb, name, fname))
            eb.add(label)
            if help:
                try:
                    eb.set_tooltip_markup('<span foreground=\"darkred\"><b>' +
                                          tools.to_xml(name) +
                                          '</b></span>\n' + tools.to_xml(help))
                except:
                    pass
                label.set_markup(
                    "<sup><span foreground=\"darkgreen\">?</span></sup>" +
                    tools.to_xml(name))
                eb.show()
            if '_' in name:
                label.set_text_with_mnemonic(name)
                label.set_mnemonic_widget(widget)
            label.set_alignment(1.0, 0.5)
            table.attach(eb,
                         x,
                         x + 1,
                         y,
                         y + rowspan,
                         yoptions=yopt,
                         xoptions=gtk.FILL,
                         ypadding=ypadding,
                         xpadding=2)
        hbox = widget
        hbox.show_all()
        if translate:
            hbox = gtk.HBox(spacing=3)
            hbox.pack_start(widget)
            img = gtk.Image()
            img.set_from_stock('terp-translate', gtk.ICON_SIZE_MENU)
            ebox = gtk.EventBox()
            ebox.set_events(gtk.gdk.BUTTON_PRESS_MASK)
            self.trans_box.append((ebox, name, fname, widget))

            ebox.add(img)
            hbox.pack_start(ebox, fill=False, expand=False)
            hbox.show_all()
        table.attach(hbox,
                     x + a,
                     x + colspan,
                     y,
                     y + rowspan,
                     yoptions=yopt,
                     ypadding=ypadding,
                     xpadding=2)
        self.cont[-1] = (table, x + colspan, y)
        wid_list = table.get_children()
        wid_list.reverse()
        table.set_focus_chain(wid_list)
        if invisible:
            hbox.hide()
Example #25
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        number = (datas.get('form', False) and datas['form']['number']) or 1
        pool = pooler.get_pool(cr.dbname)
        product_pool = pool.get('product.product')
        product_uom_pool = pool.get('product.uom')
        supplier_info_pool = pool.get('product.supplierinfo')
        workcenter_pool = pool.get('mrp.workcenter')
        user_pool = pool.get('res.users')
        bom_pool = pool.get('mrp.bom')
        pricelist_pool = pool.get('product.pricelist')
        rml_obj=report_sxw.rml_parse(cr, uid, product_pool._name,context)
        rml_obj.localcontext.update({'lang':context.get('lang',False)})
        company_currency = user_pool.browse(cr, uid, uid).company_id.currency_id
        company_currency_symbol = company_currency.symbol or company_currency.name
        def process_bom(bom, currency_id, factor=1):
            xml = '<row>'
            sum = 0
            sum_strd = 0
            prod = product_pool.browse(cr, uid, bom['product_id'])

            prod_name = to_xml(bom['name'])
            prod_qtty = factor * bom['product_qty']
            product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context)
            product_uom_name = to_xml(product_uom.name)
            main_sp_price, main_sp_name , main_strd_price = '','',''
            sellers, sellers_price = '',''

            if prod.seller_id:
                main_sp_name = '- <b>'+ to_xml(prod.seller_id.name) +'</b>\r\n'
                pricelist =  prod.seller_id.property_product_pricelist_purchase
                price = pricelist_pool.price_get(cr,uid,[pricelist.id],
                     prod.id, number*prod_qtty or 1.0, prod.seller_id.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                        })[pricelist.id]
                main_sp_price = """<b>"""+rml_obj.formatLang(price)+' '+ (company_currency_symbol)+"""</b>\r\n"""
                sum += prod_qtty*price
            std_price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, prod.cost_price, to_uom_id=product_uom.id)
            main_strd_price = str(std_price) + '\r\n'
            sum_strd = prod_qtty*std_price
            for seller_id in prod.seller_ids:
                sellers +=  '- <i>'+ to_xml(seller_id.name.name) +'</i>\r\n'
                pricelist = seller_id.name.property_product_pricelist_purchase
                price = pricelist_pool.price_get(cr,uid,[pricelist.id],
                     prod.id, number*prod_qtty or 1.0, seller_id.name.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                        })[pricelist.id]
                sellers_price += """<i>"""+rml_obj.formatLang(price) +' '+ (company_currency_symbol) +"""</i>\r\n"""
            xml += """<col para='yes'> """+ prod_name +""" </col>
                    <col para='yes'> """+ main_sp_name + sellers + """ </col>
                    <col f='yes'>"""+ rml_obj.formatLang(prod_qtty) +' '+ product_uom_name +"""</col>
                    <col f='yes'>"""+ rml_obj.formatLang(float(main_strd_price)) +' '+ (company_currency_symbol) +"""</col>
                    <col f='yes'>""" + main_sp_price + sellers_price + """</col>'"""

            xml += '</row>'
            return xml, sum, sum_strd

        def process_workcenter(wrk):
            workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id'])
            cost_cycle = wrk['cycle']*workcenter.costs_cycle
            cost_hour = wrk['hour']*workcenter.costs_hour
            total = cost_cycle + cost_hour
            xml = '<row>'
            xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>'
            xml += "<col/>"
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour)+' '+ (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour + cost_cycle)+' '+ (company_currency_symbol) + """</col>"""
            xml += '</row>'

            return xml, total


        xml = ''
        config_start = """
        <config>
            <date>""" + to_xml(rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),date_time=True)) + """</date>
            <company>%s</company>
            <PageSize>210.00mm,297.00mm</PageSize>
            <PageWidth>595.27</PageWidth>
            <PageHeight>841.88</PageHeight>
            <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize>
            """ % (user_pool.browse(cr, uid, uid).company_id.name)
        config_stop = """
            <report-footer>Generated by OpenERP</report-footer>
        </config>
        """

        workcenter_header = """
            <lines style='header'>
                <row>
                    <col>%s</col>
                    <col t='yes'/>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>
            </lines>
        """ % (_('Work Center name'), _('Cycles Cost'), _('Hourly Cost'),_('Work Cost'))
        prod_header = """
                <row>
                    <col>%s</col>
                    <col>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>
        """ % (_('Components'), _('Components suppliers'), _('Quantity'),_('Cost Price per Uom'), _('Supplier Price per Uom'))

        purchase_price_digits = rml_obj.get_digits(dp='Purchase Price')

        for product in product_pool.browse(cr, uid, ids, context=context):
            product_uom_name = to_xml(product.uom_id.name)
            bom_id = bom_pool._bom_find(cr, uid, product.id, product.uom_id.id)
            title = "<title>%s</title>" %(_("Cost Structure"))
            title += "<title>%s</title>" % (to_xml(product.name))
            xml += "<lines style='header'>" + title + prod_header + "</lines>"
            if not bom_id:
                total_strd = number * product.cost_price
                total = number * product_pool.price_get(cr, uid, [product.id], 'standard_price')[product.id]
                xml += """<lines style='lines'><row>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    </row></lines>"""
                xml += """<lines style='total'> <row>
                    <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col>
                    <col/>
                    <col f='yes'/>
                    <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col>
                    <col t='yes'>"""+ rml_obj.formatLang(total, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col>
                    </row></lines>'"""
            else:
                bom = bom_pool.browse(cr, uid, bom_id, context=context)
                factor = number * product.uom_id.factor / bom.product_uom.factor
                sub_boms = bom_pool._bom_explode(cr, uid, bom, factor / bom.product_qty)
                total = 0
                total_strd = 0
                parent_bom = {
                        'product_qty': bom.product_qty,
                        'name': bom.product_id.name,
                        'product_uom': bom.product_uom.id,
                        'product_id': bom.product_id.id
                }
                xml_tmp = ''
                for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]:
                    txt, sum, sum_strd = process_bom(sub_bom, company_currency.id)
                    xml_tmp +=  txt
                    total += sum
                    total_strd += sum_strd

                xml += "<lines style='lines'>" + xml_tmp + '</lines>'
                xml += """<lines style='sub_total'> <row>
                    <col> """ + _('Components Cost of %s %s') % (str(number), product_uom_name) + """: </col>
                    <col/>
                    <col t='yes'/>
                    <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col>
                    <col t='yes'></col>
                    </row></lines>'"""

                total2 = 0
                xml_tmp = ''
                for wrk in (sub_boms and sub_boms[1]):
                    txt, sum = process_workcenter(wrk)
                    xml_tmp += txt
                    total2 += sum
                if xml_tmp:
                    xml += workcenter_header
                    xml += "<lines style='lines'>" + xml_tmp + '</lines>'
                    xml += """<lines style='sub_total'> <row>
                    <col> """ + _('Work Cost of %s %s') % (str(number), product_uom_name) +""": </col>
                    <col/>
                    <col/>
                    <col/>
                    <col t='yes'>"""+ rml_obj.formatLang(total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) +"""</col>
                    </row></lines>'"""
                xml += """<lines style='total'> <row>
                    <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col>
                    <col/>
                    <col t='yes'/>
                    <col t='yes'>"""+ rml_obj.formatLang(total_strd+total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col>
                    <col t='yes'></col>
                    </row></lines>'"""

        xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>'

        return xml
Example #26
0
    def create(self, cr, uid, ids, datas, context):
        _divide_columns_for_matrix = 0.7
        _display_ans_in_rows = 5
        _pageSize = ('29.7cm','21.1cm')
        if datas.has_key('form') and datas['form'].get('orientation','') == 'vertical':
            if datas['form'].get('paper_size','') == 'letter':
                _pageSize = ('21.6cm','27.9cm')
            elif datas['form'].get('paper_size','') == 'legal':
                _pageSize = ('21.6cm','35.6cm')
            elif datas['form'].get('paper_size','') == 'a4':
                _pageSize = ('21.1cm','29.7cm')
        elif datas.has_key('form') and datas['form'].get('orientation','') == 'horizontal':
            if datas['form'].get('paper_size','') == 'letter':
                _pageSize = ('27.9cm','21.6cm')
            elif datas['form'].get('paper_size','') == 'legal':
                _pageSize = ('35.6cm','21.6cm')
            elif datas['form'].get('paper_size','') == 'a4':
                _pageSize = ('29.7cm','21.1cm')

        _frame_width = tools.ustr(_pageSize[0])
        _frame_height = tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.90))+'cm'
        _tbl_widths = tools.ustr(float(_pageSize[0].replace('cm','')) - float(2.10))+'cm'

        rml="""<document filename="Survey Form.pdf">
            <template pageSize="("""+_pageSize[0]+""","""+_pageSize[1]+""")" title='Survey Form' author="OpenERP S.A.([email protected])" allowSplitting="20" >
                <pageTemplate id="first">
                    <frame id="first" x1="0.0cm" y1="1.0cm" width='"""+_frame_width+"""' height='"""+_frame_height+"""'/>
                    <pageGraphics>
                        <lineMode width="1.0"/>
                        <lines>1.0cm """ + tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00)) + 'cm' + """ """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00)) + 'cm' + """</lines>
                        <lines>1.0cm """ + tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00)) +'cm'+ """ 1.0cm 1.00cm</lines>
                        <lines>""" + tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm' + """ """ + tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00)) + 'cm' + """ 1.00cm</lines>
                        <lines>1.0cm 1.00cm """ + tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" 1.00cm</lines>"""

        if datas.has_key('form') and datas['form']['page_number']:
            rml +="""
                    <fill color="gray"/>
                    <setFont name="Helvetica" size="10"/>
                    <drawRightString x='""" + tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00)) + 'cm' + """' y="0.6cm">Page : <pageNumber/> </drawRightString>"""
        rml +="""</pageGraphics>
                </pageTemplate>
            </template>
            <stylesheet>
            <blockTableStyle id="ans_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="tbl_white">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="tbl_gainsboro">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
              <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="ans_tbl_white">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="ans_tbl_gainsboro">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
              <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="page_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
              <blockBackground colorName="gray" start="0,0" stop="-1,-1"/>
              <blockTextColor colorName="white" start="0,0" stop="0,0"/>
            </blockTableStyle>
            <blockTableStyle id="title_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
              <blockBackground colorName="black" start="0,0" stop="-1,-1"/>
              <blockTextColor colorName="white" start="0,0" stop="0,0"/>
            </blockTableStyle>
            <blockTableStyle id="question_tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
            </blockTableStyle>
            <blockTableStyle id="note_table">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
            </blockTableStyle>
            <blockTableStyle id="tbl">
              <blockAlignment value="LEFT"/>
              <blockValign value="TOP"/>
              <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
              <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
            </blockTableStyle>
            <initialize>
              <paraStyle name="all" alignment="justify"/>
            </initialize>
            <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
            <paraStyle name="page" fontName="helvetica-bold" fontSize="15.0" leftIndent="0.0" textColor="white"/>
            <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
            <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
            <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="0.0"/>
            <paraStyle name="descriptive_text" fontName="helvetica" fontSize="10.0" leftIndent="0.0"/>
            <paraStyle name="answer_left" alignment="LEFT" fontName="helvetica-bold" fontSize="8.0" leftIndent="0.0"/>
            <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
            <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/>
            <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/>
            <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
            <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
        </stylesheet>
        <story>"""
        surv_obj = pooler.get_pool(cr.dbname).get('survey')
        for survey in surv_obj.browse(cr,uid,ids):
            rml += """
            <blockTable colWidths='"""+_tbl_widths+"""' style="title_tbl">
                <tr><td><para style="title">""" + to_xml(tools.ustr(survey.title)) + """</para><para style="P2"><font></font></para></td></tr>
            </blockTable>"""
            if survey.note:
                rml += """
                <para style="P2"></para>
                    <blockTable colWidths='"""+_tbl_widths+"""' style="note_table">
                        <tr><td><para style="descriptive_text">""" + to_xml(tools.ustr(survey.note)) + """</para><para style="P2"><font></font></para></td></tr>
                    </blockTable>"""

            seq = 0
            for page in survey.page_ids:
                seq += 1
                rml += """
                <blockTable colWidths='"""+_tbl_widths+"""' style="page_tbl">
                    <tr><td><para style="page">"""+ tools.ustr(seq) + """. """ + to_xml(tools.ustr(page.title)) + """</para></td></tr>
                </blockTable>"""
                if page.note:
                    rml += """<para style="P2"></para><blockTable colWidths='"""+_tbl_widths+"""' style="note_table">
                                <tr><td><para style="descriptive_text">""" + to_xml(tools.ustr(page.note or '')) + """</para></td></tr>
                            </blockTable>"""

                for que in page.question_ids:
                    cols_widhts = []
                    rml += """
                    <para style="P2"><font></font></para>
                    <blockTable colWidths='"""+_tbl_widths+"""' style="question_tbl">
                        <tr><td><para style="question">"""  + to_xml(tools.ustr(que.question)) + """</para></td></tr>
                    </blockTable>
                    <para style="P2"><font></font></para>"""
                    if que.type in ['descriptive_text']:
                        cols_widhts.append(float(_tbl_widths.replace('cm','')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths + 'cm'
                        rml += """
                        <blockTable colWidths=" """ + colWidths + """ " style="ans_tbl">
                            <tr>
                                <td>
                                <para style="descriptive_text">""" + to_xml(tools.ustr(que.descriptive_text)) + """</para>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in ['multiple_choice_multiple_ans','multiple_choice_only_one_ans']:
                        answer = []
                        for ans in que.answer_choice_ids:
                            answer.append(to_xml(tools.ustr((ans.answer))))

                        def divide_list(lst, n):
                            return [lst[i::n] for i in range(n)]

                        divide_list = divide_list(answer,_display_ans_in_rows)
                        for lst in divide_list:
                            if que.type == 'multiple_choice_multiple_ans':
                                if len(lst)<>0 and len(lst)<>int(round(float(len(answer))/_display_ans_in_rows,0)):
                                   lst.append('')
                            if not lst:
                               del divide_list[divide_list.index(lst):]
                        for divide in divide_list:
                            a = _divide_columns_for_matrix*len(divide)
                            b = float(_tbl_widths.replace('cm','')) - float(a)
                            cols_widhts = []

                            for div in range(0,len(divide)):
                                cols_widhts.append(float(a/len(divide)))
                                cols_widhts.append(float(b/len(divide)))
                            colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                            colWidths = colWidths +'cm'
                            rml+="""<blockTable colWidths=" """ + colWidths + """ " style="ans_tbl">
                                        <tr>"""
                            for div in range(0,len(divide)):
                               if divide[div] != '':
                                   if que.type == 'multiple_choice_multiple_ans':
                                           rml += """
                                           <td>
                                               <illustration>
                                                   <rect x="0.1cm" y="-0.4cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes"/>
                                                </illustration>
                                           </td>
                                           <td><para style="answer">""" + divide[div] + """</para></td>"""
                                   else:
                                       rml += """
                                       <td>
                                           <illustration>
                                               <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes"/>
                                            </illustration>
                                       </td>
                                       <td><para style="answer">""" + divide[div] + """</para></td>"""
                               else:
                                   rml += """
                                   <td></td>
                                   <td></td>"""
                            rml += """
                            </tr></blockTable>"""

                    elif que.type in ['matrix_of_choices_only_one_ans','rating_scale','matrix_of_choices_only_multi_ans','matrix_of_drop_down_menus']:
                        if len(que.column_heading_ids):
                            cols_widhts.append(float(_tbl_widths.replace('cm',''))/float(2.0))
                            for col in que.column_heading_ids:
                                cols_widhts.append(float((float(_tbl_widths.replace('cm',''))/float(2.0))/len(que.column_heading_ids)))
                        else:
                            cols_widhts.append(float(_tbl_widths.replace('cm','')))

                        tmp = 0.0
                        sum = 0.0
                        i = 0
                        if que.comment_column:
                            for col in cols_widhts:
                                if i == 0:
                                    cols_widhts[i] = cols_widhts[i]/2.0
                                    tmp = cols_widhts[i]
                                sum += col
                                i += 1
                            cols_widhts.append(round(tmp,2))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths+'cm'
                        matrix_ans = ['',]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append(col.title)
                        if que.comment_column:
                            matrix_ans.append(to_xml(tools.ustr(que.column_name)))
                        rml+="""<blockTable colWidths=" """ + colWidths + """ " style="ans_tbl"><tr>"""

                        for mat_col in matrix_ans:
                            rml += """<td><para style="response">""" + to_xml(tools.ustr(mat_col)) + """</para></td>"""
                        rml += """</tr></blockTable>"""
                        i = 0
                        for ans in que.answer_choice_ids:
                            if i%2 != 0:
                                style='ans_tbl_white'
                            else:
                                style='ans_tbl_gainsboro'
                            i += 1
                            rml += """
                            <blockTable colWidths=" """ + colWidths + """ " style='"""+style+"""'>
                            <tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>"""
                            rec_width = float((sum-tmp)*10+100)
                            value = ""

                            if que.type in ['matrix_of_drop_down_menus']:
                                value = """ <fill color="white"/>
                                    <rect x="-0.1cm" y="-0.45cm" width='""" + tools.ustr(cols_widhts[-1] - 0.5) +"cm" + """' height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/>"""
                            elif que.type in ['matrix_of_choices_only_one_ans','rating_scale']:
                                value = """ <fill color="white"/>
                                    <circle x="0.35cm" y="-0.18cm" radius="0.25 cm" fill="yes" stroke="yes"/>"""
                            else:
                                value = """ <fill color="white"/>
                                    <rect x="0.1cm" y="-0.4cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/>"""
                            for mat_col in range(1,len(matrix_ans)):
                                if matrix_ans[mat_col] == que.column_name:
                                    if mat_col == 1:
                                        rml += """
                                            <td><para style="answer_left">""" + to_xml(tools.ustr(que.column_name)) + """</para></td>"""
                                    else:
                                      rml += """<td></td>"""
                                else:
                                    rml += """<td><illustration>""" + value + """</illustration></td>"""
                            rml += """</tr></blockTable>"""

                    elif que.type in ['multiple_textboxes', 'numerical_textboxes', 'date_and_time','date','multiple_textboxes_diff_type']:
                        cols_widhts.append(float(_tbl_widths.replace('cm',''))/2)
                        cols_widhts.append(float(_tbl_widths.replace('cm',''))/2)
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = tools.ustr(colWidths) + 'cm'
                        for ans in que.answer_choice_ids:
                            rml += """<para style="P1"></para>
                            <blockTable colWidths=" """+ colWidths + """ " style="ans_tbl">
                                <tr>
                                <td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>
                                    <td>
                                    <illustration>
                                        <rect x="0.0cm" y="-0.5cm" width='""" + tools.ustr(str(cols_widhts[0] - 0.3) + "cm") + """' height="0.6cm" fill="no" stroke="yes"/>
                                    </illustration>
                                    </td>
                                </tr>
                            </blockTable>"""

                    elif que.type in ['comment']:
                        cols_widhts.append(float(_tbl_widths.replace('cm','')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        rml += """<blockTable colWidths=" """ + colWidths + """cm " style="ans_tbl">
                            <tr>
                                <td><para style="comment"><font color="white"> </font></para>
                                    <illustration>
                                        <rect x="0.1cm" y="0.3cm" width='""" + tools.ustr(str(float(colWidths) - 0.6) +'cm') + """' height="1.5cm" fill="no" stroke="yes"/>
                                    </illustration>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in ['single_textbox']:
                        cols_widhts.append(float(_tbl_widths.replace('cm','')))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        rml += """<para style="P2"><font color="white"> </font></para>
                        <blockTable colWidths=" """ + colWidths + """cm " style="ans_tbl">
                            <tr>
                                <td>
                                    <illustration>
                                        <rect x="0.2cm" y="0.3cm" width='""" + tools.ustr(str(float(colWidths) - 0.7) +'cm') + """' height="0.6cm" fill="no" stroke="yes"/>
                                    </illustration>
                                </td>
                            </tr>
                        </blockTable>"""

                    elif que.type in ['table']:
                        tbl_width = float(_tbl_widths.replace('cm',''))
                        for i in range(0,len(que.column_heading_ids)):
                            cols_widhts.append(tbl_width/float(len(que.column_heading_ids)))
                        colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                        colWidths = colWidths+'cm'
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="tbl"><tr>"""
                        for col in que.column_heading_ids:
                            rml+="""<td><para style="terp_tblheader_Details">""" + to_xml(tools.ustr(col.title)) + """</para></td>"""
                        rml += """</tr></blockTable>"""
                        i = 0
                        for r in range(0,que.no_of_rows):
                            if i%2 != 0:
                                style = 'tbl_white'
                            else:
                                style = 'tbl_gainsboro'
                            i += 1
                            rml += """<blockTable colWidths=" """  + colWidths + """ " style='"""+style+"""'><tr>"""
                            for c in que.column_heading_ids:
                               rml += """
                                <td><para style="terp_default_9"><font color="white"> </font></para></td>"""
                            rml += """</tr></blockTable>"""

            if datas.has_key('form') and not datas['form']['without_pagebreak']:
                rml += """<pageBreak/>"""
            elif not datas.has_key('form'):
                rml += """<pageBreak/>"""
            else:
                rml += """<para style="P2"><font></font></para>"""

        rml += """</story></document>"""
        report_type = datas.get('report_type', 'pdf')
        create_doc = self.generators[report_type]
        pdf = create_doc(rml, title=self.title)
        return (pdf, report_type)
    def create(self, cr, uid, ids, datas, context):
        surv_obj = pooler.get_pool(cr.dbname).get('survey')
        user_obj = pooler.get_pool(cr.dbname).get('res.users')
        rml_obj=report_sxw.rml_parse(cr, uid, surv_obj._name,context)
        company=user_obj.browse(cr,uid,[uid],context)[0].company_id

        rml ="""<document filename="Survey Analysis Report.pdf">
                <template pageSize="(595.0,842.0)" title="Survey Analysis" author="OpenERP S.A.([email protected])" allowSplitting="20">
                        <pageTemplate>
                        <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/>
                        <pageGraphics>
                        <fill color="black"/>
                        <stroke color="black"/>
                        <setFont name="DejaVu Sans" size="8"/>
                        <drawString x="1.3cm" y="28.3cm"> """+to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),date_time=True))+"""</drawString>
                        <setFont name="DejaVu Sans Bold" size="10"/>
                        <drawString x="9.8cm" y="28.3cm">"""+ to_xml(company.name) +"""</drawString>
                        <stroke color="#000000"/>
                        <lines>1.3cm 28.1cm 20cm 28.1cm</lines>
                        </pageGraphics>
                        </pageTemplate>
                  </template>
                  <stylesheet>
                    <blockTableStyle id="Table1">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table3">
                      <blockAlignment value="LEFT"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table4">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table5">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_heading">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_head_2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <initialize>
                      <paraStyle name="all" alignment="justify"/>
                    </initialize>
                    <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/>
                    <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/>
                    <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/>
                    <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
                    <paraStyle name="response-bold" fontName="Helvetica-bold" fontSize="9" alignment="RIGHT" />
                    <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/>
                    <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
                    <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/>
                    <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_default_Centre_8" fontName="Helvetica" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_default_Center_heading" fontName="Helvetica-bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
                  </stylesheet>
                  <images/>
                  """

        if datas.has_key('form') and datas['form']['survey_ids']:
           ids =  datas['form']['survey_ids']

        for survey in surv_obj.browse(cr, uid, ids):
            rml += """<story>
                    <para style="Title">Answers Summary</para>
                    <para style="Standard"><font></font></para>
                    <para style="P2">
                      <font color="white"> </font>
                    </para>
                    <blockTable colWidths="280.0,100.0,120.0" style="Table_heading">
                      <tr>
                        <td>
                          <para style="terp_tblheader_General_Centre">Survey Title </para>
                        </td>
                        <td>
                          <para style="terp_tblheader_General_Centre">Total Started Survey </para>
                        </td>
                        <td>
                          <para style="terp_tblheader_General_Centre">Total Completed Survey </para>
                        </td>
                      </tr>
                      </blockTable>
                      <blockTable colWidths="280.0,100.0,120.0" style="Table_head_2">
                      <tr>
                        <td>
                          <para style="terp_default_Centre_8">""" + to_xml(tools.ustr(survey.title)) + """</para>
                        </td>
                        <td>
                          <para style="terp_default_Centre_8">""" + str(survey.tot_start_survey) + """</para>
                        </td>
                        <td>
                          <para style="terp_default_Centre_8">""" + str(survey.tot_comp_survey) + """</para>
                        </td>
                      </tr>
                    </blockTable>
                    <para style="P2">
                      <font color="white"> </font>
                    </para>"""
            for page in survey.page_ids:
                rml += """ <blockTable colWidths="500" style="Table4">
                              <tr>
                                <td><para style="page">Page :- """ + to_xml(tools.ustr(page.title)) + """</para></td>
                              </tr>
                           </blockTable>"""
                for que in page.question_ids:
                    rml +="""<blockTable colWidths="500" style="Table5">
                              <tr>
                                <td><para style="question">"""  + to_xml(tools.ustr(que.question)) + """</para></td>
                              </tr>
                             </blockTable>"""
                    cols_widhts = []

                    if que.type in ['matrix_of_choices_only_one_ans','matrix_of_choices_only_multi_ans']:
                        cols_widhts.append(200)
                        for col in range(0, len(que.column_heading_ids) + 1):
                            cols_widhts.append(float(300 / (len(que.column_heading_ids) + 1)))
                        colWidths = ",".join(map(tools.ustr, cols_widhts))
                        matrix_ans = [(0,'')]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append((col.id,col.title))
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>"""
                        for mat_col in range(0, len(matrix_ans)):
                            rml+="""<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>"""
                        rml += """<td><para style="response-bold">Answer Count</para></td>
                                </tr>"""
                        last_col = cols_widhts[-1]

                        for ans in que.answer_choice_ids:
                            rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>"""
                            cr.execute("select count(id) from survey_response_answer sra where sra.answer_id = %s", (ans.id,))
                            tot_res = cr.fetchone()[0]
                            cr.execute("select count(id) ,sra.column_id from survey_response_answer sra where sra.answer_id=%s group by sra.column_id", (ans.id,))
                            calc_res = cr.dictfetchall()
                            for mat_col in range(1, len(matrix_ans)):
                                percantage = 0.0
                                cal_count = 0
                                for cal in calc_res:
                                    if cal['column_id'] == matrix_ans[mat_col][0]:
                                        cal_count = cal['count']
                                if tot_res:
                                    percantage = round(float(cal_count)*100 / tot_res,2)
                                if percantage:
                                    rml += """<td color="#FFF435"><para style="answer_bold">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>"""
                                else:
                                    rml += """<td color="#FFF435"><para style="answer">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>"""
                            rml += """<td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td>
                                </tr>"""
                        rml += """</blockTable>"""

                        if que.is_comment_require:
                            cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''",(que.id,))
                            tot_res = cr.fetchone()[0]
                            rml += """<blockTable colWidths=" """+ str(500 - last_col) +"," + str(last_col) + """ " style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td>
                                    <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>"""

                    elif que.type in['multiple_choice_only_one_ans', 'multiple_choice_multiple_ans', 'multiple_textboxes','date_and_time','date','multiple_textboxes_diff_type']:
                        rml += """<blockTable colWidths="240.0,210,50.0" style="Table1">"""
                        rml += """ <tr>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="terp_default_Center_heading">Answer Percentage</para></td>
                             <td> <para style="response-bold">Answer Count</para></td>
                         </tr>"""

                        for ans in que.answer_choice_ids:
                            progress = ans.average * 7 / 100
                            rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>
                                    <td>
                                    <illustration>
                                    <stroke color="lightslategray"/>
                                       <rect x="0.1cm" y="-0.45cm" width="7.2 cm" height="0.5cm" fill="no" stroke="yes"  round="0.1cm"/>
                                       """
                            if progress:
                                rml += """<fill color="lightsteelblue"/>
                                       <rect x="0.2cm" y="-0.35cm"  width='""" + tools.ustr(str(float(progress)) +'cm') + """' height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>"""
                            rml += """
                                <fill color="black"/>
                                <setFont name="Helvetica" size="9"/>
                                <drawString x="3.2cm" y="-0.30cm">"""  + tools.ustr(ans.average) + """%</drawString></illustration>
                                    </td>
                                    <td><para style="answer_right">""" + tools.ustr(ans.response) + """</para></td></tr>"""
                        rml += """</blockTable>"""

                        if que.is_comment_require:
#                            if que.make_comment_field:
#                                cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,))
#                                tot_res = cr.fetchone()[0]
#                                tot_avg = 0.00
#                                if que.tot_resp:
#                                    tot_avg = round(float(tot_res * 100)/ que.tot_resp,2)
#                                rml+="""<blockTable colWidths="280.0,120,100.0" style="Table1"><tr><td><para style="answer">""" +to_xml(tools.ustr(que.comment_label)) + """</para></td>
#                                        <td><para style="answer">""" + str(tot_avg) + """%</para></td>
#                                        <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>"""
#                            else:
                            cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,))
                            tot_res = cr.fetchone()[0]
                            rml += """<blockTable colWidths="450.0,50.0" style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td>
                                    <td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>"""

                    elif que.type in['single_textbox']:
                        cr.execute("select count(id) from survey_response_line where question_id = %s and single_text!=''",(que.id,))
                        rml += """<blockTable colWidths="400.0,100.0" style="Table1">
                             <tr>
                                 <td> <para style="Standard"> </para></td>
                                 <td> <para style="response-bold">Answer Count</para></td>
                             </tr>
                            <tr><td><para style="answer"></para></td>
                                <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr>
                            </blockTable>"""

                    elif que.type in['comment']:
                        cr.execute("select count(id) from survey_response_line where question_id = %s and comment !=''", (que.id,))
                        rml += """<blockTable colWidths="400.0,100.0" style="Table1">
                             <tr>
                                 <td> <para style="Standard"> </para></td>
                                 <td> <para style="response-bold">Answer Count</para></td>
                             </tr>
                            <tr><td><para style="answer"></para></td>
                                <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr>
                            </blockTable>"""

                    elif que.type in['rating_scale']:
                        cols_widhts.append(200)
                        for col in range(0,len(que.column_heading_ids) + 2):
                            cols_widhts.append(float(300 / (len(que.column_heading_ids) + 2)))
                        colWidths = ",".join(map(tools.ustr, cols_widhts))
                        matrix_ans = [(0,'')]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append((col.id,col.title))
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>"""
                        for mat_col in range(0,len(matrix_ans)):
                            rml += """<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>"""
                        rml += """<td><para style="response-bold">Rating Average</para></td>
                                <td><para style="response-bold">Answer Count</para></td>
                                </tr>"""

                        for ans in que.answer_choice_ids:
                            rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>"""
                            res_count = 0
                            rating_weight_sum = 0
                            for mat_col in range(1, len(matrix_ans)):
                                cr.execute("select count(sra.answer_id) from survey_response_line sr, survey_response_answer sra\
                                     where sr.id = sra.response_id and  sra.answer_id = %s and sra.column_id ='%s'", (ans.id,matrix_ans[mat_col][0]))
                                tot_res = cr.fetchone()[0]
                                cr.execute("select count(sra.answer_id),sqc.rating_weight from survey_response_line sr, survey_response_answer sra ,\
                                        survey_question_column_heading sqc where sr.id = sra.response_id and \
                                        sqc.question_id = sr.question_id  and sra.answer_id = %s and sqc.title ='%s'\
+                                       group by sra.answer_id,sqc.rating_weight", (ans.id,matrix_ans[mat_col][1]))
                                col_weight =  cr.fetchone()

                                if not col_weight:
                                    col_weight= (0,0)
                                elif not col_weight[1]:
                                    col_weight = (col_weight[0],0)
                                res_count = col_weight[0]

                                if tot_res and res_count:
                                    rating_weight_sum += int(col_weight[1]) * tot_res
                                    tot_per = round((float(tot_res) * 100) / int(res_count), 2)
                                else:
                                    tot_per = 0.0
                                if tot_res:
                                    rml += """<td><para style="answer_bold">""" + tools.ustr(tot_per) + "%(" + tools.ustr(tot_res) + """)</para></td>"""
                                else:
                                    rml += """<td><para style="answer">""" + tools.ustr(tot_per)+"%(" + tools.ustr(tot_res) + """)</para></td>"""

                            percantage = 0.00
                            if res_count:
                                percantage = round((float(rating_weight_sum)/res_count), 2)
                            rml += """<td><para style="answer_right">""" + tools.ustr(percantage) + """</para></td>
                                <td><para style="answer_right">""" + tools.ustr(res_count) + """</para></td></tr>"""
                        rml += """</blockTable>"""

                    elif que.type in['matrix_of_drop_down_menus']:
                        for column in que.column_heading_ids:
                            rml += """<blockTable colWidths="500" style="Table1"><tr>
                                <td><para style="answer">""" + to_xml(tools.ustr(column.title)) + """</para></td></tr></blockTable>"""
                            menu_choices = column.menu_choice.split('\n')
                            cols_widhts = []
                            cols_widhts.append(200)
                            for col in range(0, len(menu_choices) + 1):
                                cols_widhts.append(float(300 / (len(menu_choices) + 1)))
                            colWidths = ",".join(map(tools.ustr, cols_widhts))
                            rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>
                                <td><para style="response"></para></td>"""

                            for menu in menu_choices:
                                rml += """<td><para style="response">""" + to_xml(tools.ustr(menu)) + """</para></td>"""
                            rml += """<td><para style="response-bold">Answer Count</para></td></tr>"""
                            cr.execute("select count(id), sra.answer_id from survey_response_answer sra \
                                     where sra.column_id='%s' group by sra.answer_id ", (column.id,))
                            res_count = cr.dictfetchall()
                            cr.execute("select count(sra.id),sra.value_choice, sra.answer_id, sra.column_id from survey_response_answer sra \
                                 where sra.column_id='%s' group by sra.value_choice ,sra.answer_id, sra.column_id", (column.id,))
                            calc_percantage = cr.dictfetchall()

                            for ans in que.answer_choice_ids:
                                rml += """<tr><td><para style="answer_right">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>"""
                                for mat_col in range(0, len(menu_choices)):
                                    calc = 0
                                    response = 0
                                    for res in res_count:
                                        if res['answer_id'] == ans.id: response = res['count']
                                    for per in calc_percantage:
                                        if ans.id == per['answer_id'] and menu_choices[mat_col] == per['value_choice']:
                                            calc = per['count']
                                    percantage = 0.00

                                    if calc and response:
                                        percantage = round((float(calc)* 100) / response,2)
                                    if calc:
                                        rml += """<td><para style="answer_bold">""" +tools.ustr(percantage)+"% (" +  tools.ustr(calc) + """)</para></td>"""
                                    else:
                                        rml += """<td><para style="answer">""" +tools.ustr(percantage)+"% (" +  tools.ustr(calc) + """)</para></td>"""

                                response = 0
                                for res in res_count:
                                    if res['answer_id'] == ans.id: response = res['count']
                                rml += """<td><para style="answer_right">""" + tools.ustr(response) + """</para></td></tr>"""
                            rml += """</blockTable>"""

                    elif que.type in['numerical_textboxes']:
                        rml += """<blockTable colWidths="240.0,20,100.0,70,70.0" style="Table1">
                             <tr>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="response">Answer Average</para></td>
                             <td> <para style="response">Answer Total</para></td>
                             <td> <para style="response-bold">Answer Count</para></td>
                         </tr>"""
                        for ans in que.answer_choice_ids:
                            cr.execute("select answer from survey_response_answer where answer_id=%s group by answer", (ans.id,))
                            tot_res = cr.dictfetchall()
                            total = 0
                            for  tot in tot_res:
                                total += int(tot['answer'])
                            per = 0.00

                            if len(tot_res):
                                per = round((float(total) / len(tot_res)),2)
                            rml+="""<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>
                                    <td> <para style="Standard"> </para></td>
                                    <td> <para style="answer">""" + tools.ustr(per) +"""</para></td>
                                    <td><para style="answer">""" + tools.ustr(total) + """</para></td>
                                    <td><para style="answer_right">""" + tools.ustr(len(tot_res)) + """</para></td></tr>"""
                        rml+="""</blockTable>"""

                    rml +="""<blockTable colWidths="300,100,100.0" style="Table3">
                        <tr>
                              <td><para style="Standard1"></para></td>
                              <td><para style="Standard1">Answered Question</para></td>
                              <td><para style="Standard1">""" + tools.ustr(que.tot_resp) + """</para></td>
                        </tr>
                        <tr>
                            <td><para style="Standard1"></para></td>
                            <td><para style="Standard1">Skipped Question</para></td>
                            <td><para style="Standard1">""" + tools.ustr(survey.tot_start_survey - que.tot_resp) + """</para></td>
                        </tr>
                        </blockTable>"""
            rml += """</story>"""

        rml += """</document>"""
        report_type = datas.get('report_type', 'pdf')
        create_doc = self.generators[report_type]
        self.internal_header=True
        pdf = create_doc(rml, title=self.title)

        return (pdf, report_type)
Example #28
0
    def create_xml(self, cr, uid, ids, datas, context=None):
        number = (datas.get('form', False) and datas['form']['number']) or 1
        pool = pooler.get_pool(cr.dbname)
        product_pool = pool.get('product.product')
        product_uom_pool = pool.get('product.uom')
        supplier_info_pool = pool.get('product.supplierinfo')
        workcenter_pool = pool.get('mrp.workcenter')
        user_pool = pool.get('res.users')
        bom_pool = pool.get('mrp.bom')
        pricelist_pool = pool.get('product.pricelist')
        rml_obj = report_sxw.rml_parse(cr, uid, product_pool._name, context)
        rml_obj.localcontext.update({'lang': context.get('lang', False)})
        company_currency = user_pool.browse(cr, uid,
                                            uid).company_id.currency_id
        company_currency_symbol = company_currency.symbol or company_currency.name

        def process_bom(bom, currency_id, factor=1):
            xml = '<row>'
            sum = 0
            sum_strd = 0
            prod = product_pool.browse(cr, uid, bom['product_id'])

            prod_name = to_xml(bom['name'])
            prod_qtty = factor * bom['product_qty']
            product_uom = product_uom_pool.browse(cr,
                                                  uid,
                                                  bom['product_uom'],
                                                  context=context)
            product_uom_name = to_xml(product_uom.name)
            main_sp_price, main_sp_name, main_strd_price = '', '', ''
            sellers, sellers_price = '', ''

            if prod.seller_id:
                main_sp_name = '- <b>' + to_xml(
                    prod.seller_id.name) + '</b>\r\n'
                pricelist = prod.seller_id.property_product_pricelist_purchase
                price = pricelist_pool.price_get(
                    cr, uid, [pricelist.id], prod.id, number * prod_qtty
                    or 1.0, prod.seller_id.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                    })[pricelist.id]
                main_sp_price = """<b>""" + rml_obj.formatLang(price) + ' ' + (
                    company_currency_symbol) + """</b>\r\n"""
                sum += prod_qtty * price
            std_price = product_uom_pool._compute_price(
                cr,
                uid,
                prod.uom_id.id,
                prod.standard_price,
                to_uom_id=product_uom.id)
            main_strd_price = str(std_price) + '\r\n'
            sum_strd = prod_qtty * std_price
            for seller_id in prod.seller_ids:
                sellers += '- <i>' + to_xml(seller_id.name.name) + '</i>\r\n'
                pricelist = seller_id.name.property_product_pricelist_purchase
                price = pricelist_pool.price_get(
                    cr, uid, [pricelist.id], prod.id, number * prod_qtty
                    or 1.0, seller_id.name.id, {
                        'uom': prod.uom_po_id.id,
                        'date': time.strftime('%Y-%m-%d'),
                    })[pricelist.id]
                sellers_price += """<i>""" + rml_obj.formatLang(
                    price) + ' ' + (company_currency_symbol) + """</i>\r\n"""
            xml += """<col para='yes'> """ + prod_name + """ </col>
                    <col para='yes'> """ + main_sp_name + sellers + """ </col>
                    <col f='yes'>""" + rml_obj.formatLang(
                prod_qtty) + ' ' + product_uom_name + """</col>
                    <col f='yes'>""" + rml_obj.formatLang(
                    float(main_strd_price)) + ' ' + (
                        company_currency_symbol) + """</col>
                    <col f='yes'>""" + main_sp_price + sellers_price + """</col>'"""

            xml += '</row>'
            return xml, sum, sum_strd

        def process_workcenter(wrk):
            workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id'])
            cost_cycle = wrk['cycle'] * workcenter.costs_cycle
            cost_hour = wrk['hour'] * workcenter.costs_hour
            total = cost_cycle + cost_hour
            xml = '<row>'
            xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>'
            xml += "<col/>"
            xml += """<col f='yes'>""" + rml_obj.formatLang(
                cost_cycle) + ' ' + (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>""" + rml_obj.formatLang(
                cost_hour) + ' ' + (company_currency_symbol) + """</col>"""
            xml += """<col f='yes'>""" + rml_obj.formatLang(
                cost_hour +
                cost_cycle) + ' ' + (company_currency_symbol) + """</col>"""
            xml += '</row>'

            return xml, total

        xml = ''
        config_start = """
        <config>
            <date>""" + to_xml(
            rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                               date_time=True)) + """</date>
            <company>%s</company>
            <PageSize>210.00mm,297.00mm</PageSize>
            <PageWidth>595.27</PageWidth>
            <PageHeight>841.88</PageHeight>
            <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize>
            """ % (user_pool.browse(cr, uid, uid).company_id.name)
        config_stop = """
            <report-footer>Generated by OpenERP</report-footer>
        </config>
        """

        workcenter_header = """
            <lines style='header'>
                <row>
                    <col>%s</col>
                    <col t='yes'/>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>
            </lines>
        """ % (_('Work Center name'), _('Cycles Cost'), _('Hourly Cost'),
               _('Work Cost'))
        prod_header = """
                <row>
                    <col>%s</col>
                    <col>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                    <col t='yes'>%s</col>
                </row>
        """ % (_('Components'), _('Components suppliers'), _('Quantity'),
               _('Cost Price per Uom'), _('Supplier Price per Uom'))

        purchase_price_digits = rml_obj.get_digits(dp='Purchase Price')

        for product in product_pool.browse(cr, uid, ids, context=context):
            product_uom_name = to_xml(product.uom_id.name)
            bom_id = bom_pool._bom_find(cr, uid, product.id, product.uom_id.id)
            title = "<title>%s</title>" % (_("Cost Structure"))
            title += "<title>%s</title>" % (to_xml(product.name))
            xml += "<lines style='header'>" + title + prod_header + "</lines>"
            if not bom_id:
                total_strd = number * product.standard_price
                total = number * product_pool.price_get(
                    cr, uid, [product.id], 'standard_price')[product.id]
                xml += """<lines style='lines'><row>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    <col para='yes'>-</col>
                    </row></lines>"""
                xml += """<lines style='total'> <row>
                    <col> """ + _('Total Cost of %s %s') % (
                    str(number), product_uom_name) + """: </col>
                    <col/>
                    <col f='yes'/>
                    <col t='yes'>""" + rml_obj.formatLang(
                        total_strd, digits=purchase_price_digits) + ' ' + (
                            company_currency_symbol) + """</col>
                    <col t='yes'>""" + rml_obj.formatLang(
                                total, digits=purchase_price_digits) + ' ' + (
                                    company_currency_symbol) + """</col>
                    </row></lines>'"""
            else:
                bom = bom_pool.browse(cr, uid, bom_id, context=context)
                factor = number * product.uom_id.factor / bom.product_uom.factor
                sub_boms = bom_pool._bom_explode(cr, uid, bom,
                                                 factor / bom.product_qty)
                total = 0
                total_strd = 0
                parent_bom = {
                    'product_qty': bom.product_qty,
                    'name': bom.product_id.name,
                    'product_uom': bom.product_uom.id,
                    'product_id': bom.product_id.id
                }
                xml_tmp = ''
                for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]:
                    txt, sum, sum_strd = process_bom(sub_bom,
                                                     company_currency.id)
                    xml_tmp += txt
                    total += sum
                    total_strd += sum_strd

                xml += "<lines style='lines'>" + xml_tmp + '</lines>'
                xml += """<lines style='sub_total'> <row>
                    <col> """ + _('Components Cost of %s %s') % (
                    str(number), product_uom_name) + """: </col>
                    <col/>
                    <col t='yes'/>
                    <col t='yes'>""" + rml_obj.formatLang(
                        total_strd, digits=purchase_price_digits) + ' ' + (
                            company_currency_symbol) + """</col>
                    <col t='yes'></col>
                    </row></lines>'"""

                total2 = 0
                xml_tmp = ''
                for wrk in (sub_boms and sub_boms[1]):
                    txt, sum = process_workcenter(wrk)
                    xml_tmp += txt
                    total2 += sum
                if xml_tmp:
                    xml += workcenter_header
                    xml += "<lines style='lines'>" + xml_tmp + '</lines>'
                    xml += """<lines style='sub_total'> <row>
                    <col> """ + _('Work Cost of %s %s') % (
                        str(number), product_uom_name) + """: </col>
                    <col/>
                    <col/>
                    <col/>
                    <col t='yes'>""" + rml_obj.formatLang(
                            total2, digits=purchase_price_digits) + ' ' + (
                                company_currency_symbol) + """</col>
                    </row></lines>'"""
                xml += """<lines style='total'> <row>
                    <col> """ + _('Total Cost of %s %s') % (
                    str(number), product_uom_name) + """: </col>
                    <col/>
                    <col t='yes'/>
                    <col t='yes'>""" + rml_obj.formatLang(
                        total_strd + total2,
                        digits=purchase_price_digits) + ' ' + (
                            company_currency_symbol) + """</col>
                    <col t='yes'></col>
                    </row></lines>'"""

        xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>'

        return xml
Example #29
0
    def create(self, cr, uid, ids, datas, context):
        surv_obj = pooler.get_pool(cr.dbname).get('survey')
        user_obj = pooler.get_pool(cr.dbname).get('res.users')
        rml_obj = report_sxw.rml_parse(cr, uid, surv_obj._name, context)
        company = user_obj.browse(cr, uid, [uid], context)[0].company_id

        rml = """<document filename="Survey Analysis Report.pdf">
                <template pageSize="(595.0,842.0)" title="Survey Analysis" author="OpenERP S.A.([email protected])" allowSplitting="20">
                        <pageTemplate>
                        <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/>
                        <pageGraphics>
                        <fill color="black"/>
                        <stroke color="black"/>
                        <setFont name="DejaVu Sans" size="8"/>
                        <drawString x="1.3cm" y="28.3cm"> """ + to_xml(
            rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),
                               date_time=True)) + """</drawString>
                        <setFont name="DejaVu Sans Bold" size="10"/>
                        <drawString x="9.8cm" y="28.3cm">""" + to_xml(
                                   company.name) + """</drawString>
                        <stroke color="#000000"/>
                        <lines>1.3cm 28.1cm 20cm 28.1cm</lines>
                        </pageGraphics>
                        </pageTemplate>
                  </template>
                  <stylesheet>
                    <blockTableStyle id="Table1">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table3">
                      <blockAlignment value="LEFT"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table4">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table5">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_heading">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_head_2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <initialize>
                      <paraStyle name="all" alignment="justify"/>
                    </initialize>
                    <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/>
                    <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/>
                    <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/>
                    <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
                    <paraStyle name="response-bold" fontName="Helvetica-bold" fontSize="9" alignment="RIGHT" />
                    <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/>
                    <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
                    <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/>
                    <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_default_Centre_8" fontName="Helvetica" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_default_Center_heading" fontName="Helvetica-bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
                  </stylesheet>
                  <images/>
                  """

        if datas.has_key('form') and datas['form']['survey_ids']:
            ids = datas['form']['survey_ids']

        for survey in surv_obj.browse(cr, uid, ids):
            rml += """<story>
                    <para style="Title">Answers Summary</para>
                    <para style="Standard"><font></font></para>
                    <para style="P2">
                      <font color="white"> </font>
                    </para>
                    <blockTable colWidths="280.0,100.0,120.0" style="Table_heading">
                      <tr>
                        <td>
                          <para style="terp_tblheader_General_Centre">Survey Title </para>
                        </td>
                        <td>
                          <para style="terp_tblheader_General_Centre">Total Started Survey </para>
                        </td>
                        <td>
                          <para style="terp_tblheader_General_Centre">Total Completed Survey </para>
                        </td>
                      </tr>
                      </blockTable>
                      <blockTable colWidths="280.0,100.0,120.0" style="Table_head_2">
                      <tr>
                        <td>
                          <para style="terp_default_Centre_8">""" + to_xml(
                tools.ustr(survey.title)) + """</para>
                        </td>
                        <td>
                          <para style="terp_default_Centre_8">""" + str(
                    survey.tot_start_survey) + """</para>
                        </td>
                        <td>
                          <para style="terp_default_Centre_8">""" + str(
                        survey.tot_comp_survey) + """</para>
                        </td>
                      </tr>
                    </blockTable>
                    <para style="P2">
                      <font color="white"> </font>
                    </para>"""
            for page in survey.page_ids:
                rml += """ <blockTable colWidths="500" style="Table4">
                              <tr>
                                <td><para style="page">Page :- """ + to_xml(
                    tools.ustr(page.title)) + """</para></td>
                              </tr>
                           </blockTable>"""
                for que in page.question_ids:
                    rml += """<blockTable colWidths="500" style="Table5">
                              <tr>
                                <td><para style="question">""" + to_xml(
                        tools.ustr(que.question)) + """</para></td>
                              </tr>
                             </blockTable>"""
                    cols_widhts = []

                    if que.type in [
                            'matrix_of_choices_only_one_ans',
                            'matrix_of_choices_only_multi_ans'
                    ]:
                        cols_widhts.append(200)
                        for col in range(0, len(que.column_heading_ids) + 1):
                            cols_widhts.append(
                                float(300 / (len(que.column_heading_ids) + 1)))
                        colWidths = ",".join(map(tools.ustr, cols_widhts))
                        matrix_ans = [(0, '')]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append((col.id, col.title))
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>"""
                        for mat_col in range(0, len(matrix_ans)):
                            rml += """<td><para style="response">""" + to_xml(
                                tools.ustr(matrix_ans[mat_col]
                                           [1])) + """</para></td>"""
                        rml += """<td><para style="response-bold">Answer Count</para></td>
                                </tr>"""
                        last_col = cols_widhts[-1]

                        for ans in que.answer_choice_ids:
                            rml += """<tr><td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)) + """</para></td>"""
                            cr.execute(
                                "select count(id) from survey_response_answer sra where sra.answer_id = %s",
                                (ans.id, ))
                            tot_res = cr.fetchone()[0]
                            cr.execute(
                                "select count(id) ,sra.column_id from survey_response_answer sra where sra.answer_id=%s group by sra.column_id",
                                (ans.id, ))
                            calc_res = cr.dictfetchall()
                            for mat_col in range(1, len(matrix_ans)):
                                percantage = 0.0
                                cal_count = 0
                                for cal in calc_res:
                                    if cal['column_id'] == matrix_ans[mat_col][
                                            0]:
                                        cal_count = cal['count']
                                if tot_res:
                                    percantage = round(
                                        float(cal_count) * 100 / tot_res, 2)
                                if percantage:
                                    rml += """<td color="#FFF435"><para style="answer_bold">""" + tools.ustr(
                                        percantage) + "% (" + tools.ustr(
                                            cal_count) + """)</para></td>"""
                                else:
                                    rml += """<td color="#FFF435"><para style="answer">""" + tools.ustr(
                                        percantage) + "% (" + tools.ustr(
                                            cal_count) + """)</para></td>"""
                            rml += """<td><para style="answer_right">""" + tools.ustr(
                                tot_res) + """</para></td>
                                </tr>"""
                        rml += """</blockTable>"""

                        if que.is_comment_require:
                            cr.execute(
                                "select count(id) from survey_response_line where question_id = %s and comment != ''",
                                (que.id, ))
                            tot_res = cr.fetchone()[0]
                            rml += """<blockTable colWidths=" """ + str(
                                500 - last_col
                            ) + "," + str(
                                last_col
                            ) + """ " style="Table1"><tr><td><para style="answer_right">""" + to_xml(
                                tools.ustr(que.comment_label)
                            ) + """</para></td>
                                    <td><para style="answer">""" + tools.ustr(
                                tot_res) + """</para></td></tr></blockTable>"""

                    elif que.type in [
                            'multiple_choice_only_one_ans',
                            'multiple_choice_multiple_ans',
                            'multiple_textboxes', 'date_and_time', 'date',
                            'multiple_textboxes_diff_type'
                    ]:
                        rml += """<blockTable colWidths="240.0,210,50.0" style="Table1">"""
                        rml += """ <tr>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="terp_default_Center_heading">Answer Percentage</para></td>
                             <td> <para style="response-bold">Answer Count</para></td>
                         </tr>"""

                        for ans in que.answer_choice_ids:
                            progress = ans.average * 7 / 100
                            rml += """<tr><td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)) + """</para></td>
                                    <td>
                                    <illustration>
                                    <stroke color="lightslategray"/>
                                       <rect x="0.1cm" y="-0.45cm" width="7.2 cm" height="0.5cm" fill="no" stroke="yes"  round="0.1cm"/>
                                       """
                            if progress:
                                rml += """<fill color="lightsteelblue"/>
                                       <rect x="0.2cm" y="-0.35cm"  width='""" + tools.ustr(
                                    str(float(progress)) + 'cm'
                                ) + """' height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>"""
                            rml += """
                                <fill color="black"/>
                                <setFont name="Helvetica" size="9"/>
                                <drawString x="3.2cm" y="-0.30cm">""" + tools.ustr(
                                ans.average) + """%</drawString></illustration>
                                    </td>
                                    <td><para style="answer_right">""" + tools.ustr(
                                    ans.response) + """</para></td></tr>"""
                        rml += """</blockTable>"""

                        if que.is_comment_require:
                            #                            if que.make_comment_field:
                            #                                cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,))
                            #                                tot_res = cr.fetchone()[0]
                            #                                tot_avg = 0.00
                            #                                if que.tot_resp:
                            #                                    tot_avg = round(float(tot_res * 100)/ que.tot_resp,2)
                            #                                rml+="""<blockTable colWidths="280.0,120,100.0" style="Table1"><tr><td><para style="answer">""" +to_xml(tools.ustr(que.comment_label)) + """</para></td>
                            #                                        <td><para style="answer">""" + str(tot_avg) + """%</para></td>
                            #                                        <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>"""
                            #                            else:
                            cr.execute(
                                "select count(id) from survey_response_line where question_id = %s and comment != ''",
                                (que.id, ))
                            tot_res = cr.fetchone()[0]
                            rml += """<blockTable colWidths="450.0,50.0" style="Table1"><tr><td><para style="answer_right">""" + to_xml(
                                tools.ustr(que.comment_label)
                            ) + """</para></td>
                                    <td><para style="answer_right">""" + tools.ustr(
                                tot_res) + """</para></td></tr></blockTable>"""

                    elif que.type in ['single_textbox']:
                        cr.execute(
                            "select count(id) from survey_response_line where question_id = %s and single_text!=''",
                            (que.id, ))
                        rml += """<blockTable colWidths="400.0,100.0" style="Table1">
                             <tr>
                                 <td> <para style="Standard"> </para></td>
                                 <td> <para style="response-bold">Answer Count</para></td>
                             </tr>
                            <tr><td><para style="answer"></para></td>
                                <td><para style="answer_right">""" + tools.ustr(
                            cr.fetchone()[0]) + """ </para></td></tr>
                            </blockTable>"""

                    elif que.type in ['comment']:
                        cr.execute(
                            "select count(id) from survey_response_line where question_id = %s and comment !=''",
                            (que.id, ))
                        rml += """<blockTable colWidths="400.0,100.0" style="Table1">
                             <tr>
                                 <td> <para style="Standard"> </para></td>
                                 <td> <para style="response-bold">Answer Count</para></td>
                             </tr>
                            <tr><td><para style="answer"></para></td>
                                <td><para style="answer_right">""" + tools.ustr(
                            cr.fetchone()[0]) + """ </para></td></tr>
                            </blockTable>"""

                    elif que.type in ['rating_scale']:
                        cols_widhts.append(200)
                        for col in range(0, len(que.column_heading_ids) + 2):
                            cols_widhts.append(
                                float(300 / (len(que.column_heading_ids) + 2)))
                        colWidths = ",".join(map(tools.ustr, cols_widhts))
                        matrix_ans = [(0, '')]

                        for col in que.column_heading_ids:
                            if col.title not in matrix_ans:
                                matrix_ans.append((col.id, col.title))
                        rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>"""
                        for mat_col in range(0, len(matrix_ans)):
                            rml += """<td><para style="response">""" + to_xml(
                                tools.ustr(matrix_ans[mat_col]
                                           [1])) + """</para></td>"""
                        rml += """<td><para style="response-bold">Rating Average</para></td>
                                <td><para style="response-bold">Answer Count</para></td>
                                </tr>"""

                        for ans in que.answer_choice_ids:
                            rml += """<tr><td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)) + """</para></td>"""
                            res_count = 0
                            rating_weight_sum = 0
                            for mat_col in range(1, len(matrix_ans)):
                                cr.execute(
                                    "select count(sra.answer_id) from survey_response_line sr, survey_response_answer sra\
                                     where sr.id = sra.response_id and  sra.answer_id = %s and sra.column_id ='%s'",
                                    (ans.id, matrix_ans[mat_col][0]))
                                tot_res = cr.fetchone()[0]
                                cr.execute(
                                    "select count(sra.answer_id),sqc.rating_weight from survey_response_line sr, survey_response_answer sra ,\
                                        survey_question_column_heading sqc where sr.id = sra.response_id and \
                                        sqc.question_id = sr.question_id  and sra.answer_id = %s and sqc.title ='%s'\
+                                       group by sra.answer_id,sqc.rating_weight",
                                    (ans.id, matrix_ans[mat_col][1]))
                                col_weight = cr.fetchone()

                                if not col_weight:
                                    col_weight = (0, 0)
                                elif not col_weight[1]:
                                    col_weight = (col_weight[0], 0)
                                res_count = col_weight[0]

                                if tot_res and res_count:
                                    rating_weight_sum += int(
                                        col_weight[1]) * tot_res
                                    tot_per = round((float(tot_res) * 100) /
                                                    int(res_count), 2)
                                else:
                                    tot_per = 0.0
                                if tot_res:
                                    rml += """<td><para style="answer_bold">""" + tools.ustr(
                                        tot_per) + "%(" + tools.ustr(
                                            tot_res) + """)</para></td>"""
                                else:
                                    rml += """<td><para style="answer">""" + tools.ustr(
                                        tot_per) + "%(" + tools.ustr(
                                            tot_res) + """)</para></td>"""

                            percantage = 0.00
                            if res_count:
                                percantage = round(
                                    (float(rating_weight_sum) / res_count), 2)
                            rml += """<td><para style="answer_right">""" + tools.ustr(
                                percantage) + """</para></td>
                                <td><para style="answer_right">""" + tools.ustr(
                                    res_count) + """</para></td></tr>"""
                        rml += """</blockTable>"""

                    elif que.type in ['matrix_of_drop_down_menus']:
                        for column in que.column_heading_ids:
                            rml += """<blockTable colWidths="500" style="Table1"><tr>
                                <td><para style="answer">""" + to_xml(
                                tools.ustr(column.title)
                            ) + """</para></td></tr></blockTable>"""
                            menu_choices = column.menu_choice.split('\n')
                            cols_widhts = []
                            cols_widhts.append(200)
                            for col in range(0, len(menu_choices) + 1):
                                cols_widhts.append(
                                    float(300 / (len(menu_choices) + 1)))
                            colWidths = ",".join(map(tools.ustr, cols_widhts))
                            rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>
                                <td><para style="response"></para></td>"""

                            for menu in menu_choices:
                                rml += """<td><para style="response">""" + to_xml(
                                    tools.ustr(menu)) + """</para></td>"""
                            rml += """<td><para style="response-bold">Answer Count</para></td></tr>"""
                            cr.execute(
                                "select count(id), sra.answer_id from survey_response_answer sra \
                                     where sra.column_id='%s' group by sra.answer_id ",
                                (column.id, ))
                            res_count = cr.dictfetchall()
                            cr.execute(
                                "select count(sra.id),sra.value_choice, sra.answer_id, sra.column_id from survey_response_answer sra \
                                 where sra.column_id='%s' group by sra.value_choice ,sra.answer_id, sra.column_id",
                                (column.id, ))
                            calc_percantage = cr.dictfetchall()

                            for ans in que.answer_choice_ids:
                                rml += """<tr><td><para style="answer_right">""" + to_xml(
                                    tools.ustr(
                                        ans.answer)) + """</para></td>"""
                                for mat_col in range(0, len(menu_choices)):
                                    calc = 0
                                    response = 0
                                    for res in res_count:
                                        if res['answer_id'] == ans.id:
                                            response = res['count']
                                    for per in calc_percantage:
                                        if ans.id == per[
                                                'answer_id'] and menu_choices[
                                                    mat_col] == per[
                                                        'value_choice']:
                                            calc = per['count']
                                    percantage = 0.00

                                    if calc and response:
                                        percantage = round(
                                            (float(calc) * 100) / response, 2)
                                    if calc:
                                        rml += """<td><para style="answer_bold">""" + tools.ustr(
                                            percantage) + "% (" + tools.ustr(
                                                calc) + """)</para></td>"""
                                    else:
                                        rml += """<td><para style="answer">""" + tools.ustr(
                                            percantage) + "% (" + tools.ustr(
                                                calc) + """)</para></td>"""

                                response = 0
                                for res in res_count:
                                    if res['answer_id'] == ans.id:
                                        response = res['count']
                                rml += """<td><para style="answer_right">""" + tools.ustr(
                                    response) + """</para></td></tr>"""
                            rml += """</blockTable>"""

                    elif que.type in ['numerical_textboxes']:
                        rml += """<blockTable colWidths="240.0,20,100.0,70,70.0" style="Table1">
                             <tr>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="Standard"> </para></td>
                             <td> <para style="response">Answer Average</para></td>
                             <td> <para style="response">Answer Total</para></td>
                             <td> <para style="response-bold">Answer Count</para></td>
                         </tr>"""
                        for ans in que.answer_choice_ids:
                            cr.execute(
                                "select answer from survey_response_answer where answer_id=%s group by answer",
                                (ans.id, ))
                            tot_res = cr.dictfetchall()
                            total = 0
                            for tot in tot_res:
                                total += int(tot['answer'])
                            per = 0.00

                            if len(tot_res):
                                per = round((float(total) / len(tot_res)), 2)
                            rml += """<tr><td><para style="answer">""" + to_xml(
                                tools.ustr(ans.answer)) + """</para></td>
                                    <td> <para style="Standard"> </para></td>
                                    <td> <para style="answer">""" + tools.ustr(
                                    per) + """</para></td>
                                    <td><para style="answer">""" + tools.ustr(
                                        total) + """</para></td>
                                    <td><para style="answer_right">""" + tools.ustr(
                                            len(tot_res)
                                        ) + """</para></td></tr>"""
                        rml += """</blockTable>"""

                    rml += """<blockTable colWidths="300,100,100.0" style="Table3">
                        <tr>
                              <td><para style="Standard1"></para></td>
                              <td><para style="Standard1">Answered Question</para></td>
                              <td><para style="Standard1">""" + tools.ustr(
                        que.tot_resp) + """</para></td>
                        </tr>
                        <tr>
                            <td><para style="Standard1"></para></td>
                            <td><para style="Standard1">Skipped Question</para></td>
                            <td><para style="Standard1">""" + tools.ustr(
                            survey.tot_start_survey -
                            que.tot_resp) + """</para></td>
                        </tr>
                        </blockTable>"""
            rml += """</story>"""

        rml += """</document>"""
        report_type = datas.get('report_type', 'pdf')
        create_doc = self.generators[report_type]
        self.internal_header = True
        pdf = create_doc(rml, title=self.title)

        return (pdf, report_type)
Example #30
0
 def display(self, widget):
     if self.treeview:
         if self.value:
             self.treeview.warn('misc-message', '<b>' + str(tools.to_xml(self.value))+"</b>")
         else:
             self.treeview.warn('misc-message', _("Press <i>'+'</i>, <i>'-'</i> or <i>'='</i> for special date operations."))
Example #31
0
def _str_2_rml(s):
    return to_xml(tools.ustr(s or ''))
    def create(self, cr, uid, ids, datas, context):
        _divide_columns_for_matrix = 0.7
        _display_ans_in_rows = 5
        _pageSize = ("29.7cm", "21.1cm")

        if datas.has_key("form") and datas["form"].get("orientation", "") == "vertical":
            if datas["form"].get("paper_size", "") == "letter":
                _pageSize = ("21.6cm", "27.9cm")
            elif datas["form"].get("paper_size", "") == "legal":
                _pageSize = ("21.6cm", "35.6cm")
            elif datas["form"].get("paper_size", "") == "a4":
                _pageSize = ("21.1cm", "29.7cm")

        elif datas.has_key("form") and datas["form"].get("orientation", False) == "horizontal":
            if datas["form"].get("paper_size", "") == "letter":
                _pageSize = ("27.9cm", "21.6cm")
            elif datas["form"].get("paper_size", "") == "legal":
                _pageSize = ("35.6cm", "21.6cm")
            elif datas["form"].get("paper_size") == "a4":
                _pageSize = ("29.7cm", "21.1cm")

        _frame_width = tools.ustr(_pageSize[0])
        _frame_height = tools.ustr(float(_pageSize[1].replace("cm", "")) - float(1.90)) + "cm"
        _tbl_widths = tools.ustr(float(_pageSize[0].replace("cm", "")) - float(2.10)) + "cm"
        rml = (
            """<document filename="Survey Answer Report.pdf">
                <template pageSize="("""
            + _pageSize[0]
            + ""","""
            + _pageSize[1]
            + """)" title='Survey Answer' author="OpenERP S.A.([email protected])" allowSplitting="20" >
                    <pageTemplate id="first">
                        <frame id="first" x1="0.0cm" y1="1.0cm" width='"""
            + _frame_width
            + """' height='"""
            + _frame_height
            + """'/>
                        <pageGraphics>
                            <lineMode width="1.0"/>
                            <lines>1.0cm """
            + tools.ustr(float(_pageSize[1].replace("cm", "")) - float(1.00))
            + "cm"
            + """ """
            + tools.ustr(float(_pageSize[0].replace("cm", "")) - float(1.00))
            + "cm"
            + """ """
            + tools.ustr(float(_pageSize[1].replace("cm", "")) - float(1.00))
            + "cm"
            + """</lines>
                            <lines>1.0cm """
            + tools.ustr(float(_pageSize[1].replace("cm", "")) - float(1.00))
            + "cm"
            + """ 1.0cm 1.00cm</lines>
                            <lines>"""
            + tools.ustr(float(_pageSize[0].replace("cm", "")) - float(1.00))
            + "cm"
            + """ """
            + tools.ustr(float(_pageSize[1].replace("cm", "")) - float(1.00))
            + "cm"
            + """ """
            + tools.ustr(float(_pageSize[0].replace("cm", "")) - float(1.00))
            + "cm"
            + """ 1.00cm</lines>
                            <lines>1.0cm 1.00cm """
            + tools.ustr(float(_pageSize[0].replace("cm", "")) - float(1.00))
            + "cm"
            + """ 1.00cm</lines>"""
        )
        if datas.has_key("form") and datas["form"]["page_number"]:
            rml += (
                """
                    <fill color="gray"/>
                    <setFont name="Helvetica" size="10"/>
                    <drawRightString x='"""
                + tools.ustr(float(_pageSize[0].replace("cm", "")) - float(1.00))
                + "cm"
                + """' y="0.6cm">Page : <pageNumber/> </drawRightString>"""
            )
        rml += """</pageGraphics>
                    </pageTemplate>
                </template>
                  <stylesheet>
                    <blockTableStyle id="tbl_white">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="tbl_gainsboro">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="ans_tbl_white">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="ans_tbl_gainsboro">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="simple_table">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/>
                    </blockTableStyle>
                    <blockTableStyle id="note_table">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table2">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table3">
                      <blockAlignment value="LEFT"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table4">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table5">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table41">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table51">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/>
                      <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/>
                    </blockTableStyle>
                    <blockTableStyle id="Table_heading">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                    </blockTableStyle>
                    <blockTableStyle id="title_tbl">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                      <blockBackground colorName="black" start="0,0" stop="-1,-1"/>
                      <blockTextColor colorName="white" start="0,0" stop="0,0"/>
                    </blockTableStyle>
                    <blockTableStyle id="page_tbl">
                      <blockAlignment value="LEFT"/>
                      <blockValign value="TOP"/>
                      <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/>
                      <blockBackground colorName="gray" start="0,0" stop="-1,-1"/>
                      <blockTextColor colorName="white" start="0,0" stop="0,0"/>
                    </blockTableStyle>
                    <initialize>
                      <paraStyle name="all" alignment="justify"/>
                    </initialize>
                    <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
                    <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/>
                    <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/>
                    <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/>
                    <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/>
                    <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/>
                    <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/>
                    <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="answer1" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/>
                    <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/>
                    <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/>
                    <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_default_9_Bold" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/>
                    <paraStyle name="terp_tblheader_General_Centre_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_right_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="terp_tblheader_General_right" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/>
                    <paraStyle name="descriptive_text" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/>
                    <paraStyle name="descriptive_text_heading" fontName="helvetica-bold" fontSize="18.0" alignment="RIGHT" leftIndent="0.0" textColor="white"/>
                  </stylesheet>
                  <images/>
                  <story>"""
        surv_resp_obj = pooler.get_pool(cr.dbname).get("survey.response")
        rml_obj = report_sxw.rml_parse(cr, uid, surv_resp_obj._name, context)
        if datas.has_key("form") and datas["form"].has_key("response_ids"):
            response_id = datas["form"]["response_ids"]
        elif context.has_key("response_id") and context["response_id"]:
            response_id = [int(context["response_id"][0])]
        else:
            response_id = surv_resp_obj.search(cr, uid, [("survey_id", "in", ids)])

        surv_resp_line_obj = pooler.get_pool(cr.dbname).get("survey.response.line")
        surv_obj = pooler.get_pool(cr.dbname).get("survey")

        for response in surv_resp_obj.browse(cr, uid, response_id):
            for survey in surv_obj.browse(cr, uid, [response.survey_id.id]):
                tbl_width = float(_tbl_widths.replace("cm", ""))
                colwidth = "2.5cm,4.8cm," + str(tbl_width - 15.0) + "cm,3.2cm,4.5cm"
                resp_create = tools.ustr(
                    time.strftime(
                        "%d-%m-%Y %I:%M:%S %p", time.strptime(response.date_create.split(".")[0], "%Y-%m-%d %H:%M:%S")
                    )
                )
                rml += (
                    """<blockTable colWidths='"""
                    + colwidth
                    + """' style="Table_heading">
                          <tr>
                            <td><para style="terp_default_9_Bold">Print Date : </para></td>
                            <td><para style="terp_default_9">"""
                    + to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"), date_time=True))
                    + """</para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9_Bold">Answered by : </para></td>
                            <td><para style="terp_default_9">"""
                    + to_xml(response.user_id.login or "")
                    + """</para></td>
                          </tr>
                          <tr>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9"></para></td>
                            <td><para style="terp_default_9_Bold">Answer Date : </para></td>
                            <td><para style="terp_default_9">"""
                    + to_xml(resp_create)
                    + """</para></td>
                          </tr>
                        </blockTable><para style="P2"></para>"""
                )

                status = "Not Finished"
                if response.state == "done":
                    status = "Finished"
                colwidth = str(tbl_width - 7) + "cm,"
                colwidth += "7cm"
                rml += (
                    """<blockTable colWidths='"""
                    + str(colwidth)
                    + """' style="title_tbl">
                            <tr>
                            <td><para style="title">"""
                    + to_xml(tools.ustr(survey.title))
                    + """</para><para style="P2"><font></font></para></td>
                            <td><para style="descriptive_text_heading">Status :- """
                    + to_xml(tools.ustr(status))
                    + """</para><para style="P2"><font></font></para></td>
                            </tr>
                        </blockTable>"""
                )

                if survey.note:
                    rml += (
                        """<blockTable colWidths='"""
                        + _tbl_widths
                        + """' style="note_table">
                            <tr><td><para style="response">"""
                        + to_xml(tools.ustr(survey.note or ""))
                        + """</para><para style="P2"><font></font></para></td></tr>
                        </blockTable>"""
                    )

                for page in survey.page_ids:
                    rml += (
                        """<blockTable colWidths='"""
                        + str(_tbl_widths)
                        + """' style="page_tbl">
                                  <tr><td><para style="page">Page :- """
                        + to_xml(tools.ustr(page.title or ""))
                        + """</para></td></tr>
                              </blockTable>"""
                    )
                    if page.note:
                        rml += (
                            """<para style="P2"></para>
                                 <blockTable colWidths='"""
                            + str(_tbl_widths)
                            + """' style="note_table">
                                      <tr><td><para style="response">"""
                            + to_xml(tools.ustr(page.note or ""))
                            + """</para></td></tr>
                                 </blockTable>"""
                        )

                    for que in page.question_ids:
                        rml += (
                            """<para style="P2"></para>
                                <blockTable colWidths='"""
                            + str(_tbl_widths)
                            + """' style="Table5">
                                  <tr><td><para style="question">"""
                            + to_xml(to_xml(que.question))
                            + """</para></td></tr>
                                </blockTable>"""
                        )

                        answer = surv_resp_line_obj.browse(
                            cr,
                            uid,
                            surv_resp_line_obj.search(
                                cr, uid, [("question_id", "=", que.id), ("response_id", "=", response.id)]
                            ),
                        )
                        if que.type in ["descriptive_text"]:
                            rml += (
                                """<blockTable colWidths='"""
                                + str(_tbl_widths)
                                + """' style="simple_table">
                                         <tr><td> <para style="response">"""
                                + to_xml(tools.ustr(que.descriptive_text))
                                + """</para></td> </tr>
                                    </blockTable>"""
                            )

                        elif que.type in ["table"]:
                            if len(answer) and answer[0].state == "done":
                                col_heading = pooler.get_pool(cr.dbname).get("survey.tbl.column.heading")
                                cols_widhts = []
                                tbl_width = float(_tbl_widths.replace("cm", ""))
                                for i in range(0, len(que.column_heading_ids)):
                                    cols_widhts.append(tbl_width / float(len(que.column_heading_ids)))
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = colWidths + "cm"
                                matrix_ans = []
                                rml += (
                                    """<para style="P2"></para><blockTable colWidths=" """
                                    + str(colWidths)
                                    + """ " style="Table41"><tr>"""
                                )

                                for col in que.column_heading_ids:
                                    if col.title not in matrix_ans:
                                        matrix_ans.append(col.title)
                                        rml += (
                                            """<td> <para style="terp_tblheader_Details">"""
                                            + to_xml(tools.ustr(col.title))
                                            + """</para></td>"""
                                        )
                                rml += """</tr></blockTable>"""
                                i = 0

                                for row in range(0, que.no_of_rows):
                                    if i % 2 != 0:
                                        style = "tbl_white"
                                    else:
                                        style = "tbl_gainsboro"
                                    i += 1
                                    rml += (
                                        """<blockTable colWidths=" """
                                        + str(colWidths)
                                        + """ " style='"""
                                        + style
                                        + """'><tr>"""
                                    )
                                    table_data = col_heading.browse(
                                        cr,
                                        uid,
                                        col_heading.search(
                                            cr, uid, [("response_table_id", "=", answer[0].id), ("name", "=", row)]
                                        ),
                                    )
                                    for column in matrix_ans:
                                        value = False
                                        for col in table_data:
                                            if column == col.column_id.title:
                                                value = col.value
                                        if value:
                                            rml += (
                                                """<td> <para style="terp_default_9">"""
                                                + to_xml(tools.ustr(value))
                                                + """</para></td>"""
                                            )
                                        else:
                                            rml += """<td><para style="terp_default_9"><font color ="white"> </font></para></td>"""
                                    rml += """</tr></blockTable>"""

                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                             <tr><td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""
                                )

                        elif que.type in ["multiple_choice_only_one_ans", "multiple_choice_multiple_ans"]:
                            if len(answer) and answer[0].state == "done":
                                ans_list = []
                                for ans in answer[0].response_answer_ids:
                                    ans_list.append(to_xml(tools.ustr(ans.answer_id.answer)))
                                answer_choice = []

                                for ans in que["answer_choice_ids"]:
                                    answer_choice.append(to_xml(tools.ustr((ans.answer))))

                                def divide_list(lst, n):
                                    return [lst[i::n] for i in range(n)]

                                divide_list = divide_list(answer_choice, _display_ans_in_rows)
                                for lst in divide_list:
                                    if que.type == "multiple_choice_multiple_ans":
                                        if len(lst) <> 0 and len(lst) <> int(
                                            round(float(len(answer_choice)) / _display_ans_in_rows, 0)
                                        ):
                                            lst.append("")
                                    if not lst:
                                        del divide_list[divide_list.index(lst) :]

                                for divide in divide_list:
                                    a = _divide_columns_for_matrix * len(divide)
                                    b = float(_tbl_widths.replace("cm", "")) - float(a)
                                    cols_widhts = []
                                    for div in range(0, len(divide)):
                                        cols_widhts.append(float(a / len(divide)))
                                        cols_widhts.append(float(b / len(divide)))
                                    colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                    colWidths = colWidths + "cm"
                                    rml += (
                                        """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>"""
                                    )

                                    for div in range(0, len(divide)):
                                        if divide[div] != "":
                                            if que.type == "multiple_choice_multiple_ans":
                                                if divide[div] in ans_list:
                                                    rml += (
                                                        """<td><illustration><fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                <fill color="gray"/>
                                                                <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>
                                                                </illustration></td>
                                                             <td><para style="answer">"""
                                                        + divide[div]
                                                        + """</para></td>"""
                                                    )
                                                else:
                                                    rml += (
                                                        """<td><illustration>
                                                           <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes"  round="0.1cm"/>
                                                            </illustration></td>
                                                           <td><para style="answer">"""
                                                        + divide[div]
                                                        + """</para></td>"""
                                                    )
                                            else:
                                                if divide[div] in ans_list:
                                                    rml += (
                                                        """<td><illustration><fill color="white"/>
                                                            <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/>
                                                            <fill color="gray"/>
                                                            <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no" round="0.1cm"/>
                                                        </illustration></td>
                                                   <td><para style="answer">"""
                                                        + divide[div]
                                                        + """</para></td>"""
                                                    )
                                                else:
                                                    rml += (
                                                        """<td>
                                                               <illustration>
                                                                   <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes" round="0.1cm"/>
                                                                </illustration>
                                                           </td>
                                                           <td><para style="answer">"""
                                                        + divide[div]
                                                        + """</para></td>"""
                                                    )
                                        else:
                                            rml += """<td></td><td></td>"""
                                    rml += """</tr></blockTable>"""

                                if que.is_comment_require and answer[0].comment:
                                    rml += (
                                        """<blockTable colWidths='"""
                                        + str(_tbl_widths)
                                        + """' style="simple_table"><tr>
                                                <td><para style="answer">"""
                                        + to_xml(tools.ustr(answer[0].comment))
                                        + """</para></td></tr></blockTable>"""
                                    )
                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                             <tr><td> <para style="response">No Answer</para></td> </tr>
                                          </blockTable>"""
                                )

                        elif que.type in [
                            "multiple_textboxes_diff_type",
                            "multiple_textboxes",
                            "date",
                            "date_and_time",
                            "numerical_textboxes",
                            "multiple_textboxes_diff_type",
                        ]:
                            if len(answer) and answer[0].state == "done":
                                cols_widhts = []
                                cols_widhts.append(float(_tbl_widths.replace("cm", "")) / 2)
                                cols_widhts.append(float(_tbl_widths.replace("cm", "")) / 2)
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = tools.ustr(colWidths) + "cm"
                                answer_list = {}

                                for ans in answer[0].response_answer_ids:
                                    answer_list[ans.answer_id.answer] = ans.answer
                                for que_ans in que["answer_choice_ids"]:
                                    if que_ans.answer in answer_list:
                                        rml += (
                                            """<blockTable colWidths='"""
                                            + str(colWidths)
                                            + """' style="simple_table">
                                                 <tr> <td> <para style="response">"""
                                            + to_xml(tools.ustr(que_ans.answer))
                                            + """</para></td>
                                                 <td> <para style="response">"""
                                            + to_xml(tools.ustr(answer_list[que_ans.answer]))
                                            + """</para></td></tr>
                                                </blockTable>"""
                                        )
                                    else:
                                        rml += (
                                            """<blockTable colWidths='"""
                                            + str(colWidths)
                                            + """' style="simple_table">
                                                 <tr> <td> <para style="response">"""
                                            + to_xml(tools.ustr(que_ans.answer))
                                            + """</para></td>
                                                 <td> <para style="response"></para></td></tr>
                                                </blockTable>"""
                                        )
                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""
                                )

                        elif que.type in ["single_textbox"]:
                            if len(answer) and answer[0].state == "done":
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr> <td> <para style="response">"""
                                    + to_xml(tools.ustr(answer[0].single_text))
                                    + """</para></td></tr>
                                        </blockTable>"""
                                )
                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""
                                )

                        elif que.type in ["comment"]:
                            if len(answer) and answer[0].state == "done":
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr> <td> <para style="response">"""
                                    + to_xml(tools.ustr(answer[0].comment))
                                    + """</para></td></tr>
                                        </blockTable>"""
                                )
                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr>  <td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""
                                )

                        elif que.type in [
                            "matrix_of_choices_only_one_ans",
                            "matrix_of_choices_only_multi_ans",
                            "rating_scale",
                            "matrix_of_drop_down_menus",
                        ]:
                            if len(answer) and answer[0].state == "done":
                                if (
                                    que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]
                                    and que.comment_column
                                ):
                                    pass
                                cols_widhts = []
                                if len(que.column_heading_ids):
                                    cols_widhts.append(float(_tbl_widths.replace("cm", "")) / float(2.0))
                                    for col in que.column_heading_ids:
                                        cols_widhts.append(
                                            float(
                                                (float(_tbl_widths.replace("cm", "")) / float(2.0))
                                                / len(que.column_heading_ids)
                                            )
                                        )
                                else:
                                    cols_widhts.append(float(_tbl_widths.replace("cm", "")))

                                tmp = 0.0
                                sum = 0.0
                                i = 0
                                if (
                                    que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]
                                    and que.comment_column
                                ):
                                    for col in cols_widhts:
                                        if i == 0:
                                            cols_widhts[i] = cols_widhts[i] / 2.0
                                            tmp = cols_widhts[i]
                                        sum += col
                                        i += 1
                                    cols_widhts.append(round(tmp, 2))
                                colWidths = "cm,".join(map(tools.ustr, cols_widhts))
                                colWidths = colWidths + "cm"
                                matrix_ans = [(0, "")]

                                for col in que.column_heading_ids:
                                    if col.title not in matrix_ans:
                                        matrix_ans.append((col.id, col.title))
                                len_matrix = len(matrix_ans)
                                if (
                                    que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]
                                    and que.comment_column
                                ):
                                    matrix_ans.append((0, que.column_name))
                                rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>"""

                                for mat_col in range(0, len(matrix_ans)):
                                    rml += (
                                        """<td><para style="response">"""
                                        + to_xml(tools.ustr(matrix_ans[mat_col][1]))
                                        + """</para></td>"""
                                    )
                                rml += """</tr>"""
                                rml += """</blockTable>"""
                                i = 0

                                for ans in que.answer_choice_ids:
                                    if i % 2 != 0:
                                        style = "ans_tbl_white"
                                    else:
                                        style = "ans_tbl_gainsboro"
                                    i += 1
                                    rml += (
                                        """<blockTable colWidths=" """
                                        + colWidths
                                        + """ " style='"""
                                        + style
                                        + """'>
                                            <tr><td><para style="response">"""
                                        + to_xml(tools.ustr(ans.answer))
                                        + """</para></td>"""
                                    )
                                    comment_value = ""
                                    for mat_col in range(1, len_matrix):
                                        value = """"""
                                        for res_ans in answer[0].response_answer_ids:
                                            if (
                                                res_ans.answer_id.id == ans.id
                                                and res_ans.column_id.id == matrix_ans[mat_col][0]
                                            ):
                                                comment_value = to_xml(tools.ustr(res_ans.comment_field))
                                                if que.type in ["matrix_of_drop_down_menus"]:
                                                    value = (
                                                        """<para style="response">"""
                                                        + to_xml(tools.ustr(res_ans.value_choice))
                                                        + """</para>"""
                                                    )
                                                elif que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]:
                                                    value = """<illustration><fill color="white"/>
                                                                <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"/>
                                                                <fill color="gray"/>
                                                                <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no"/>
                                                            </illustration>"""
                                                elif que.type in ["matrix_of_choices_only_multi_ans"]:
                                                    value = """<illustration>
                                                                <fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                <fill color="gray"/>
                                                                <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no"  round="0.1cm"/>
                                                                </illustration>"""
                                                break
                                            else:
                                                if que.type in ["matrix_of_drop_down_menus"]:
                                                    value = """"""
                                                elif que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]:
                                                    value = """<illustration><fill color="white"/>
                                                                    <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                </illustration>"""
                                                elif que.type in ["matrix_of_choices_only_multi_ans"]:
                                                    value = """<illustration><fill color="white"/>
                                                                <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes"  round="0.1cm"/>
                                                                </illustration>"""
                                        rml += """<td>""" + value + """</td>"""
                                    if (
                                        que.type in ["matrix_of_choices_only_one_ans", "rating_scale"]
                                        and que.comment_column
                                    ):
                                        if comment_value == "False":
                                            comment_value = ""
                                        rml += (
                                            """<td><para style="response">"""
                                            + to_xml(tools.ustr(comment_value))
                                            + """</para></td>"""
                                        )
                                    rml += """</tr></blockTable>"""

                                if que.is_comment_require:
                                    rml += (
                                        """<blockTable colWidths='"""
                                        + str(_tbl_widths)
                                        + """' style="simple_table"><tr>
                                            <td><para style="answer">"""
                                        + to_xml(tools.ustr(answer[0].comment or ""))
                                        + """</para></td></tr></blockTable>"""
                                    )
                            else:
                                rml += (
                                    """<blockTable colWidths='"""
                                    + str(_tbl_widths)
                                    + """' style="simple_table">
                                         <tr><td> <para style="response">No Answer</para></td> </tr>
                                        </blockTable>"""
                                )

                if datas.has_key("form") and not datas["form"]["without_pagebreak"]:
                    rml += """<pageBreak/>"""
                elif not datas.has_key("form"):
                    rml += """<pageBreak/>"""
                else:
                    rml += """<para style="P2"><font></font></para>"""

        rml += """</story></document>"""
        report_type = datas.get("report_type", "pdf")
        create_doc = self.generators[report_type]
        pdf = create_doc(rml, title=self.title)
        return (pdf, report_type)
Example #33
0
 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False):
     if context is None:
         context = {}
     setting_obj = self.pool.get('hr.evaluation.setting')
     values_obj = self.pool.get('hr.evaluation.values')
     sett_obj = self.pool.get('hr.evaluation.setting')
     criteria_obj = self.pool.get('hr.evaluation.criteria')
     values_ids = values_obj.search(cr,uid,[])
     res = {}
     setting_id = context.get('active_id', False)
     if not setting_id:
         setting_id = context.get('setting_id', False)
     cols = ['criteria_id', 'form_id', 'text_criteria', 'rating']
     flag='y'
     r_only = 1
     has_group = [x.name for x in self.pool.get('res.users').browse(cr,uid,uid).groups_id if x.name=='Human Resources / Manager']
     if has_group:
         r_only = 0
     section_name = ''
     if (view_type =='form'):
         res['arch'] = """<?xml version="1.0"?>
             <form string="Evaluation Form">
             <field name="name" select = "1"/>
             <field name="employee_id" select = "1" readonly = "%d"/>
             <field name="setting_id" select = "2" readonly = "%d" />
             <field name="employee_id2" select = "2" readonly = "%d"/>
             <newline/>
             <notebook colspan = "4">
         """%(r_only, r_only, r_only)
         _Section_list = []
         set_ids = []
         if setting_id:
             for field in setting_obj.browse(cr,uid, setting_id).criteria_ids:
                 _tmp_list = []
                 _tmp_list_id = []
                 set_ids = []
                 seq = []
                 if (field.section_id and field.section_id.name) not in _Section_list:
                     _Section_list.append(field.section_id and field.section_id.name)
                     _tmp_list.append(field.section_id and field.section_id.name)
                     _tmp_list_id.append(field.section_id and field.section_id.id)
                 if _tmp_list:
                     for i in setting_obj.browse(cr, uid, setting_id).criteria_ids:
                         if i.section_id:
                             if i.section_id.id == _tmp_list_id[0]:
                                 set_ids.append(i.id)
                                 seq.append((i.sequence,i.id))
                     first_page = res['arch'].find('<page')
                     last_page = res['arch'].find('</page>')
                     if first_page != -1:
                         res['arch'] +="""</page>"""
                         res['arch'] += """
                             <page string="%s">"""%(field.section_id and field.section_id.name or '')
                     if flag == 'y':
                         flag = ''
                         res['arch'] += """
                             <page string="%s">"""%(field.section_id and field.section_id.name or '')
                 res['arch']+="""
                     """
                 set_ids = [l[1] for l in seq if l]
                 for field in criteria_obj.browse(cr,uid, set_ids):
                     if field.active:
                         res['arch']+="""<group col="1" colspan="2">
                                         <separator colspan="2" string="%s"/>
                                         <label string="%s" align="0.0"/>
                                         """%(to_xml(field.name),to_xml(field.desc_criteria or ''),)
                         if field.format_text:
                             res['arch'] += """<field name="val_q_%d" nolabel="1"/>
                                             <newline/>
                                             """%(field.id)
                         if field.format_select:
                             res['arch'] += """<label string="Rating" align="0.0"/>
                                             <newline/>"""
                             res['arch'] += """<field name="rating_%d" nolabel="1"/>"""%(field.id)
                         res['arch'] += """</group>"""
         first_page = res['arch'].find('<page')
         last_page = res['arch'].find('</page>')
         if not res['arch'].endswith('</page>') and (first_page!=-1) :
             res['arch'] +="""</page>"""
         res['arch'] += """</notebook>
                 <separator colspan="4" string="Note"/>
                 <field name="note"  colspan="4" nolabel = "1"/>
         """
         res['arch'] += """ <group colspan="4" col="5" >
                 <field name="state" select="1" readonly="1"/>
                 <button name="button_done" string="Con_firm" type="object" states="draft" />
                 <button name="button_cancel" string="Can_cel" type="object"  states="draft,done,review"/>
                 <button name="button_review" string="Re_viewed by top management" type="object" states="done"/>
                  </group>"""
         res['arch'] += "</form>"
         res['fields'] = self.fields_get(cr, uid, cols, context)
     else:
         res = super(hr_evaluation_form,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar)
     return res