Ejemplo n.º 1
0
    def create(self, cr, uid, data, context=None):
        plan_term_obj = self.pool.get('cd.plan.term')
        cd_config_obj = self.pool.get('cd.config.settings')
        cd_config_id = cd_config_obj.search(cr, uid, [])
        config = cd_config_obj.browse(cr, uid, cd_config_id[-1])
        vals_term = {
            'year':
            data['year'],
            'month':
            data['month'],
            'mark_start':
            datetime.date(data['year'], int(data['month']), 1) -
            timedelta(weeks=config.start_mark),
            'mark_stop':
            datetime.date(data['year'], int(data['month']), 1) -
            timedelta(weeks=config.stop_mark),
            'sale_start':
            datetime.date(data['year'], int(data['month']), 1) -
            timedelta(weeks=config.start_sale),
            'sale_stop':
            datetime.date(data['year'], int(data['month']), 1) -
            timedelta(weeks=config.stop_sale),
        }
        plan_term_id = plan_term_obj.create(cr, uid, vals_term)

        vals_list = []
        if self.search(cr, uid, [('month', '=', data['month']),
                                 ('year', '=', data['year'])]):
            raise osv.except_osv(
                decode('Ostrzeżenie'),
                decode(
                    'Plan Makteting Miesiąc na wybrany miesiąc już jest w systemie'
                ))

        plan_mark_obj = self.pool.get('cd.plan.mark')
        if 'plan_month_ids' in data:
            for vals in data['plan_month_ids']:
                vals_list.append(vals[2])
            del data['plan_month_ids']

        data['plan_term_id'] = plan_term_id

        plan_id = super(cd_plan_mark_month, self).create(cr,
                                                         uid,
                                                         data,
                                                         context=context)

        #Usunięcie dodawania Administratora do obserwarotów
        self.message_unsubscribe(cr, uid, [plan_id], [3], context=None)

        if vals_list:
            for val in vals_list:
                val['year'] = data['year']
                val['month'] = data['month']
                val['plan_mark_month_id'] = plan_id
                plan_mark_obj.create(cr, uid, val)

        return plan_id
Ejemplo n.º 2
0
    def add_listing(self, cr, uid, ids, context=None):
        listing_obj = self.pool.get('cd.listing')
        w = self.browse(cr, uid, ids)[0]

        listing_search = [('product_id', '=', w.new_product_id.id),
                          ('status_l', '=', '1'),
                          ('client_id', '=', w.client_id.id)]
        if w.format_id:
            listing_search.append(('fclient_id', '=', w.format_id.id))
        #else:
        #format_ids = [format.id for format in w.client_id.cformat]
        #listing_search.append(('fclient_id','in',format_ids))

        #Blokowanie wprowadzenia listingu który już istnieje
        if listing_obj.search(cr, uid, listing_search):
            raise osv.except_osv(decode('Ostrzeżenie'),
                                 decode('Ten listing już istnieje.'))

        create_vals = {
            'product_id': w.new_product_id.id,
            'client_id': w.client_id.id,
            'change_date': w.start_date,
            'status_l': '1',
            #'price_sale': w.price,
        }

        format_ids = []
        if w.format_id:
            format_ids = [w.format_id.id]
        else:
            format_ids = [format.id for format in w.client_id.cformat]

        if format_ids:
            for format_id in format_ids:
                create_vals['fclient_id'] = format_id
                listing_obj.create(cr, uid, create_vals, context=None)
        else:
            listing_obj.create(cr, uid, create_vals, context=None)

        if w.on_top == False:
            write_vals = {}
            write_vals = {
                'change_date': w.end_date,
                'status_l': '2',
            }
            if w.format_id:
                listing_id = listing_obj.search(
                    cr, uid, [('product_id', '=', w.old_product_id.id),
                              ('fclient_id', '=', w.format_id.id)])
            else:
                listing_id = listing_obj.search(
                    cr, uid, [('product_id', '=', w.old_product_id.id)])

            listing_obj.write(cr, uid, listing_id, write_vals, context=None)

        return True
Ejemplo n.º 3
0
 def on_change_start_date(self, cr, uid, vals, start_date, context=None):
     cd_config_obj = self.pool.get('cd.config.settings')
     cd_config_id = cd_config_obj.search(cr, uid, [])
     cd_plan_prom = cd_config_obj.browse(cr, uid, cd_config_id[-1]).plan_prom
     
     date_min = datetime.date.today()+timedelta(days=cd_plan_prom)
     start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d").date()
     if date_min > start_date:
         raise osv.except_osv(decode('Błąd'), decode('Minimalna data rozpoczęcia to:\n %s')%date_min.strftime("%d.%m.%Y"))
     return True
Ejemplo n.º 4
0
 def add_product(self, cr, uid, ids, context=None):
     w = self.browse(cr, uid, ids[0])
     data = {}
     data['product_id'] = w.product_id.id
     
     for product in w.product_rel_ids:
         if product.product_id.id == w.product_id.id:
             raise osv.except_osv(decode('Ostrzeżenie'), decode('Ten produkt został już dodany.'))
     data['promotions_id'] = ids[0]
     self.pool.get('cd.product.rel').create(cr, uid, data, context=None)
     vals = {}
     vals['product_id'] = False
     self.write(cr, uid, ids, vals, context=None)
     return {'value': vals}
Ejemplo n.º 5
0
    def write(self, cr, uid, ids, data, context=None):
        for id in ids:
            plan_client = self.browse(cr, uid, id)

            if 'month' in data or 'year' in data:
                month = ''
                year = 0
                if 'month' in data:
                    month = data['month']
                else:
                    month = plan_client.month
                if 'year' in data:
                    year = data['year']
                else:
                    year = plan_client.year
                if self.search(
                        cr, uid,
                    [('year', '=', year), ('month', '=', month),
                     ('section_id', '=', plan_client.section_id.id)]):
                    raise osv.except_osv(
                        decode('Ostrzeżenie'),
                        decode(
                            'Plan Klient na wybrany miesiąc już jest w systemie'
                        ))

                start_date = datetime.date(year, int(month), 1)
                stop_date = (self.add_months(start_date,
                                             1)) - timedelta(days=1)
                data['start_date'] = start_date
                data['stop_date'] = stop_date
                """
                cd_config_obj = self.pool.get('cd.config.settings')
                cd_config_id = cd_config_obj.search(cr, uid, [])
                cd_plan_prom = cd_config_obj.browse(cr, uid, cd_config_id[-1]).plan_plan_prom
                
                next_date = self.add_months(datetime.date.today(),cd_plan_prom)
                if next_date >= start_date:
                    raise osv.except_osv(decode('Ostrzeżenie'), decode('Plan Klient nie może zostać utworzony w tym terminie'))
                """
        plan_id = super(cd_plan_client, self).write(cr,
                                                    uid,
                                                    ids,
                                                    data,
                                                    context=context)

        if 'state_id' in data:
            self.copy_data(cr, SUPERUSER_ID, ids[0], context=None)

        return plan_id
Ejemplo n.º 6
0
 def message_find_partners(self,
                           cr,
                           uid,
                           message,
                           header_fields=['From'],
                           context=None):
     """ Find partner for supplier invoice. Problem is that either the
     sender (from), or the receiver (to, cc) must be a supplier, but this
     method is called first to determine the sender/author_id, and only
     later for the receiver (partner_ids). To handle this we will also
     search - as a fallback - partners that are not suppliers. Only later
     we need to check that either the sender, or the receiver is a
     supplier.
     NOT a private method (no _ prefix), because called from mail_thread.
     """
     # Find partners, taking company into account, and having a preference
     # for suppliers.
     # Each email will return one or zero partners. Unless an
     # email address occurs in multiple headers.
     company_id = (('force_company' in context and context['force_company'])
                   or False)
     partner_ids = []
     s = ', '.join(
         [decode(message.get(h)) for h in header_fields if message.get(h)])
     for email_address in tools.email_split(s):
         partner_ids += self.get_partner_from_mail(cr,
                                                   uid,
                                                   email_address,
                                                   company_id,
                                                   context=context)
     return partner_ids
Ejemplo n.º 7
0
 def accept_promotions(self, cr, uid, ids, context=None):
     stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=', 30)])[0]
     vals = {}
     vals['stage_id'] = stage_id
     self.write(cr, uid, ids, vals)
     
     mail_to = ''
     promotion = self.browse(cr, uid, ids[0])
     if promotion.create_uid.email and promotion.create_uid.email != '':
         mail_to += promotion.create_uid.email+', '
         
     """
     if promotion.margin_warning == False:
         users_obj = self.pool.get('res.users')
         group_id = self.pool.get('res.groups').search(cr,uid,[('name','=','Sales Director')])
         user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
         for user in users_obj.browse(cr, uid, user_ids):
             if user.email and user.email != '':
                 mail_to += user.email+', '
     """    
     if mail_to != '':
         cd_config_obj = self.pool.get('cd.config.settings')
         cd_config_id = cd_config_obj.search(cr, uid, [])
         cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
         url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
         subject = 'Akcja promocyjna została zaakceptowana.'
         vals = (promotion.client_id.name, url)                
         body = decode("Akcja promocyjna klienta %s została zaakceptowana.<br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
         self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
     return True
Ejemplo n.º 8
0
 def _message_extract_payload_receipt(self, message,
                                      save_original=False):
     """Extract body as HTML and attachments from the mail message"""
     attachments = []
     body = u''
     if save_original:
         attachments.append(('original_email.eml', message.as_string()))
     if not message.is_multipart() or \
             'text/' in message.get('content-type', ''):
         encoding = message.get_content_charset()
         body = message.get_payload(decode=True)
         body = tools.ustr(body, encoding, errors='replace')
         if message.get_content_type() == 'text/plain':
             # text/plain -> <pre/>
             body = tools.append_content_to_html(u'', body, preserve=True)
     else:
         alternative = False
         for part in message.walk():
             if part.get_content_type() == 'multipart/alternative':
                 alternative = True
             if part.get_content_maintype() == 'multipart':
                 continue  # skip container
             filename = part.get_param('filename',
                                       None,
                                       'content-disposition')
             if not filename:
                 filename = part.get_param('name', None)
             if filename:
                 if isinstance(filename, tuple):
                     # RFC2231
                     filename = email.utils.collapse_rfc2231_value(
                         filename).strip()
                 else:
                     filename = decode(filename)
             encoding = part.get_content_charset()  # None if attachment
             # 1) Explicit Attachments -> attachments
             if filename or part.get('content-disposition', '')\
                     .strip().startswith('attachment'):
                 attachments.append((filename or 'attachment',
                                     part.get_payload(decode=True))
                                    )
                 continue
             # 2) text/plain -> <pre/>
             if part.get_content_type() == 'text/plain' and \
                     (not alternative or not body):
                 body = tools.append_content_to_html(
                     body,
                     tools.ustr(part.get_payload(decode=True),
                                encoding, errors='replace'),
                     preserve=True)
             # 3) text/html -> raw
             elif part.get_content_type() == 'text/html':
                 continue
             # 4) Anything else -> attachment
             else:
                 attachments.append((filename or 'attachment',
                                     part.get_payload(decode=True))
                                    )
     return body, attachments
Ejemplo n.º 9
0
 def add_product(self, cr, uid, ids, context=None):
     w = self.browse(cr, uid, ids[0])
     data = {}
     data['product_id'] = w.product_id.id
     for product in w.plan_product_ids:
         if product.product_id.id == w.product_id.id:
             raise osv.except_osv(decode('Ostrzeżenie'),
                                  decode('Ten produkt został już dodany.'))
     data['plan_client_id'] = ids[0]
     data['plan_value'] = 0.0
     data['year'] = w.year
     data['month'] = w.month
     self.pool.get('cd.plan.product').create(cr, uid, data, context=None)
     vals = {}
     vals['product_id'] = False
     self.write(cr, uid, ids, vals, context=None)
     return {'value': vals}
Ejemplo n.º 10
0
    def message_parse(self, cr, uid, message, save_original=False, context=None):
        msg_dict = super(MailThread, self).message_parse(
            cr, uid, message, save_original=save_original, context=context)

        if message.get('Reply-To'):
            msg_dict['reply_to'] = decode(message.get('Reply-To'))

        return msg_dict
Ejemplo n.º 11
0
 def message_route_process(self, cr, uid, message, message_dict, routes, context=None):
     """ Override to update the parent mail statistics. The parent is found
     by using the References header of the incoming message and looking for
     matching message_id in mail.mail.statistics. """
     if message.get('References'):
         message_ids = [x.strip() for x in decode(message['References']).split()]
         self.pool['mail.mail.statistics'].set_replied(cr, uid, mail_message_ids=message_ids, context=context)
     return super(MailThread, self).message_route_process(cr, uid, message, message_dict, routes, context=context)
Ejemplo n.º 12
0
 def message_route_process(self, cr, uid, message, message_dict, routes, context=None):
     """ Override to update the parent mail statistics. The parent is found
     by using the References header of the incoming message and looking for
     matching message_id in mail.mail.statistics. """
     if message.get('References'):
         message_ids = [x.strip() for x in decode(message['References']).split()]
         self.pool['mail.mail.statistics'].set_replied(cr, uid, mail_message_ids=message_ids, context=context)
     return super(MailThread, self).message_route_process(cr, uid, message, message_dict, routes, context=context)
Ejemplo n.º 13
0
 def create(self, cr, uid, data, context=None):
     other_obj = self.pool.get('cd.other.cogs')
     product_obj = self.pool.get('product.product')
     
     for product_id in data['product_ids'][0][2]:
         product = product_obj.browse(cr, uid, product_id)
         if other_obj.search(cr, uid, [('product_id','=',product_id),('plan_client_id','=',context['active_id'])]):
             raise osv.except_osv(decode('Ostrzeżenie'), decode('Produkt: %s został już dodany.')%product.name)
         vals = {}
         vals = {
                 'product_id': product_id,
                 'count': 0, 
                 'settled': '01',
                 'plan_client_id': context['active_id']
                 }
         other_obj.create(cr, uid, vals, context=None)
         
     return 1
Ejemplo n.º 14
0
    def create(self, cr, uid, data, context=None):
        #pdb.set_trace()
        if self.search(cr, uid, [('year', '=', data['year']),
                                 ('month', '=', data['month']),
                                 ('client_id', '=', data['client_id'])]):
            raise osv.except_osv(
                decode('Ostrzeżenie'),
                decode('Plan Klient na wybrany miesiąc już jest w systemie'))

        start_date = datetime.date(data['year'], int(data['month']), 1)
        stop_date = (self.add_months(start_date, 1)) - timedelta(days=1)
        data['start_date'] = start_date
        data['stop_date'] = stop_date
        """
        cd_config_obj = self.pool.get('cd.config.settings')
        cd_config_id = cd_config_obj.search(cr, uid, [])
        cd_plan_prom = cd_config_obj.browse(cr, uid, cd_config_id[-1]).plan_plan_prom
        
        next_date = self.add_months(datetime.date.today(),cd_plan_prom)
        if next_date >= start_date:
            raise osv.except_osv(decode('Ostrzeżenie'), decode('Plan Klient nie może zostać utworzony w tym terminie'))
        """

        plan_id = super(cd_plan_client, self).create(cr,
                                                     uid,
                                                     data,
                                                     context=context)

        #Usunięcie dodawania Administratora do obserwarotów
        self.message_unsubscribe(cr, uid, [plan_id], [3], context=None)

        plan_client = self.browse(cr, uid, plan_id)

        if plan_client.client_id.user_id.partner_id:
            self.message_subscribe(
                cr,
                uid, [plan_id], [plan_client.client_id.user_id.partner_id.id],
                context=context)

        self.add_products2(cr, uid, plan_id)
        #print data['month'] + " " + plan_client.client_id.name
        #self.add_products2(cr, uid, plan_id)
        return plan_id
Ejemplo n.º 15
0
 def _get_num2word(self, cr, uid, ids, fields, arg, context=None):
     res = {}
     for account in self.browse(cr, uid, ids):
         cents = int(round((account.amount_total-int(account.amount_total)),2)*100)
         str_cents = num2word(cents, 'pl_PL')+' groszy'
         string = ''
         
         string = num2word(int(account.amount_total), 'pl_PL')
         res[account.id] = string+decode(' złotych ') + str_cents
     return res
Ejemplo n.º 16
0
 def _get_num2word(self, cr, uid, ids, fields, arg, context=None):
     res = {}
     for voucher in self.browse(cr, uid, ids):
         cents = int(round((voucher.amount-int(voucher.amount)),2)*100)
         str_cents = num2word(cents, 'pl_PL')+' groszy'
         string = ''
         
         string = num2word(int(voucher.amount), 'pl_PL')
         res[voucher.id] = string+decode(' złotych ') + str_cents
     return res
Ejemplo n.º 17
0
 def notification_start_date(self, cr, uid, context=None):
     start_date = datetime.date.today()+timedelta(days=10)
     promotions_ids = self.search(cr, uid, [('start_date','=',start_date),('sequence','=',50)])
     #powiadomienie na 10 dni przed rozpoczęciem do PH
     for promotion in self.browse(cr, uid, promotions_ids):
         mail_to = ''
         for affiliate in promotion.client_id.affiliate_ids:
             if affiliate.ph_user_id and affiliate.ph_user_id.email:
                 mail_to += affiliate.ph_user_id.email+', '
         if mail_to != '':
             cd_config_obj = self.pool.get('cd.config.settings')
             cd_config_id = cd_config_obj.search(cr, uid, [])
             cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
             url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
             vals = (promotion.client_id.name, url)
             subject = 'Rozpoczęcie akcji promocyjnej'
             body = decode("Za 10 dni rozpocznie się akcja promocyjna dla Twojego klienta %s <br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
             self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
                 
     promotions_mon_ids = self.search(cr, uid, [('start_date','=',start_date),('sequence','=',50),('monitored','=',True)])
     #powiadomienie jeżeli monitorowana na 10 dni przed rozpoczęciem do TMS i TMM
     for promotion in self.browse(cr, uid, promotions_mon_ids):
         users_obj = self.pool.get('res.users')
         group_id = self.pool.get('res.groups').search(cr,uid,[('name','=','Trade Marketing Manager')])
         user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
         users = users_obj.browse(cr, uid, user_ids)
         mail_to = ''
         for user in users:
             if user.email and user.email != '':
                 mail_to += user.email+', '
         tms_user = promotion.client_id.section_id.tms_user_id
         if tms_user.email:
             mail_to += tms_user.email
         if mail_to != '':
             cd_config_obj = self.pool.get('cd.config.settings')
             cd_config_id = cd_config_obj.search(cr, uid, [])
             cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
             url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
             vals = (promotion.client_id.name, url)
             subject = 'Rozpoczęcie akcji promocyjnej'
             body = decode("Za 10 dni rozpocznie się akcja promocyjna dla klienta %s <br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
             self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
     return True
Ejemplo n.º 18
0
    def create(self, cr, uid, data, context=None):
        product_rel_obj = self.pool.get('cd.product.rel')
        product_obj = self.pool.get('product.product')

        for product_id in data['product_ids'][0][2]:
            product = product_obj.browse(cr, uid, product_id)
            if product_rel_obj.search(
                    cr, uid, [('product_id', '=', product_id),
                              ('promotions_id', '=', context['active_id'])]):
                raise osv.except_osv(
                    decode('Ostrzeżenie'),
                    decode('Produkt: %s został już dodany.') % product.name)
            vals = {}
            vals = {
                'product_id': product_id,
                'promotions_id': context['active_id'],
            }
            product_rel_obj.create(cr, uid, vals, context=None)

        return False
Ejemplo n.º 19
0
 def change_stage(self, cr, uid, context=None):
     cd_config_obj = self.pool.get('cd.config.settings')
     cd_config_id = cd_config_obj.search(cr, uid, [])
     plan_prom = cd_config_obj.browse(cr, uid, cd_config_id[-1]).plan_prom
     date = datetime.date.today()+timedelta(days=plan_prom)
     today = datetime.date.today()
     
     #Zaakceptowana -> Anulowana
     promotions_ids = self.search(cr, uid, [('sequence','in',[30]), ('start_date','<=', date)])
     if promotions_ids:
         stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=',90)])[0]
         for promotion in self.browse(cr, uid, promotions_ids):
             vals = {}
             vals['stage_id'] = stage_id
             self.write(cr, uid, [promotion.id], vals)
     #Do akceptacji -> Odrzucona
     promotions_ids_2 = self.search(cr, uid, [('sequence','in',[20]), ('start_date','<=', date)])
     if promotions_ids_2:
         stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=',40)])[0]
         for promotion in self.browse(cr, uid, promotions_ids_2):
             vals = {}
             vals['stage_id'] = stage_id
             self.write(cr, uid, [promotion.id], vals)
     #Potwierdzona -> W trakcie
     promotions_ids_3 = self.search(cr, uid, [('sequence','in',[50]), ('start_date','=', today)])
     if promotions_ids_3:
         stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=',60)])[0]
         for promotion in self.browse(cr, uid, promotions_ids_3):
             vals = {}
             vals['stage_id'] = stage_id
             self.write(cr, uid, [promotion.id], vals)
     #W trakcie -> Zakończona
     promotions_ids_4 = self.search(cr, uid, [('sequence','in',[60]), ('stop_date','=', today)])
     if promotions_ids_4:
         stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=',70)])[0]
         for promotion in self.browse(cr, uid, promotions_ids_4):
             vals = {}
             vals['stage_id'] = stage_id
             self.write(cr, uid, [promotion.id], vals)
             mail_to = ''
             if promotion.create_uid and promotion.create_uid != '':
                 mail_to += promotion.create_uid.email+', '
             if mail_to != '':
                 cd_config_obj = self.pool.get('cd.config.settings')
                 cd_config_id = cd_config_obj.search(cr, uid, [])
                 cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
                 url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
                 subject = 'Akcja promocyjna została zakończona.'
                 vals = (promotion.client_id.name, url)                
                 body = decode("Akcja promocyjna klienta %s została zakończona i oczekuje na rozliczenie.<br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
                 self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
             
     return True
Ejemplo n.º 20
0
    def to_invoice(self, cr, uid, ids, context=None):
        lead_obj = self.pool.get('crm.lead')
        context['lead_ids'] = self.get_lead_to_invoice(cr, uid, context['active_ids'])
        if not context['lead_ids']:
            raise osv.except_osv(decode('Ostrzeżenie'), decode('Nie wybrano właściwych szans'))
        
        invoice_lines = []
        for lead in lead_obj.browse(cr, uid, context['lead_ids']):
            if lead.partner_sale_id:
                context['default_partner_id'] = lead.partner_sale_id.id
            invoice_line = {
                            'product_id': 1,
                            'name': lead.name,
                            'ppiu_product_id': lead.product_id.id,
                            'price_unit': lead.provision_value
                            }
            invoice_lines.append([0, False, invoice_line])
            
        if 'default_partner_id' in context:
            context['default_invoice_line'] = invoice_lines
                
        ir_model_data = self.pool.get('ir.model.data')
        form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
        form_id = form_res and form_res[1] or False
        tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree')
        tree_id = tree_res and tree_res[1] or False

        return {
            'name': 'Faktura',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'account.invoice',
            'res_id': False,
            'view_id': False,
            'views': [(form_id, 'form'), (tree_id, 'tree')],
            'type': 'ir.actions.act_window',
            'context': context
        }
    def message_parse(self, cr, uid, message, save_original=False, context=None):
        '''' parse reply-to and set author_id to reply-to partner '''
        result = super(mail_thread, self).message_parse(cr, uid, message, save_original, context)
        if not isinstance(message, Message):
            if isinstance(message, unicode):
                # Warning: message_from_string doesn't always work correctly on unicode,
                # we must use utf-8 strings here :-(
                message = message.encode('utf-8')
            message = email.message_from_string(message)
        result['reply-to'] = decode(message.get('Reply-To'))
        if message.get('Reply-To'):
            author_ids = self._message_find_partners(cr, uid, message, ['Reply-To'], context=context)
            if author_ids:
                result['author_id'] = author_ids[0]

        return result
Ejemplo n.º 22
0
 def rejected_promotions(self, cr, uid, ids, context=None):
     stage_id = self.pool.get('cd.promotions.stage').search(cr, uid, [('sequence','=', 90)])[0]
     vals = {}
     vals['stage_id'] = stage_id
     self.write(cr, uid, ids, vals)
     mail_to = ''
     promotion = self.browse(cr, uid, ids[0])
     if promotion.create_uid.email and promotion.create_uid.email != '':
         mail_to += promotion.create_uid.email+', '
     if mail_to != '':
         cd_config_obj = self.pool.get('cd.config.settings')
         cd_config_id = cd_config_obj.search(cr, uid, [])
         cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
         url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
         subject = 'Akcja promocyjna została odrzucona.'
         vals = (promotion.client_id.name, url)                
         body = decode("Akcja promocyjna klienta %s została odrzucona.<br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
         self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
Ejemplo n.º 23
0
    def _get_msg_payload(self, cr, uid, msg, parts=None, num=0):
        """
        This method recursively checks the message structure and
            saves the informations (bodies, attachments,
            pkcs7 signatures, etc.) in a dictionary.

        The method parameters are:

         - msg is the multipart message to process; the first time
         the method is called it is exactly the Original.eml message,
         that is: the email as it arrives from the imap server.
         The method is called recursively when a multipart structure is
         found, in this case msg is a multipart inside the Original.eml
         message and the num param is the depth of the multipart inside
         the Original.eml message.
         - parts is the dictionary where the informations are saved
         - num is an integer that refers to the depth
            of the msg content in the Original.eml message

        Some examples of the structure for the different kind of pec messages
        can be found in the docs folder of this module

        """
        if parts is None:
            parts = {}
        for part in msg.get_payload():
            filename = part.get_param('filename', None, 'content-disposition')
            if not filename:
                filename = part.get_param('name', None)
            if filename:
                if isinstance(filename, tuple):
                    # RFC2231
                    filename = email.utils.collapse_rfc2231_value(
                        filename).strip()
                else:
                    filename = decode(filename)
            # Returns the files for a normal pec email
            if num == 0 and part.get_content_type() == \
                    'application/x-pkcs7-signature' and \
                    filename == 'smime.p7s':
                parts['smime.p7s'] = part.get_payload(decode=True)
            elif num == 1 and part.get_content_type() == \
                    'application/xml' and \
                    filename == 'daticert.xml':
                parts['daticert.xml'] = part.get_payload(decode=True)
            elif num == 1 and part.get_content_type() == \
                    'message/rfc822' and \
                    filename == 'postacert.eml':
                parts['postacert.eml'] = part.get_payload()[0]
            # If something went wrong: get basic info of the original message
            elif part.get_content_type() == \
                    'multipart/report':
                parts['report'] = True
            elif part.get_content_type() == \
                    'message/delivery-status':
                parts['delivery-status'] = self._get_msg_delivery(part)
            # If rfc822-headers is found get original msg info from payload
            elif part.get_content_type() == \
                    'text/rfc822-headers':
                parts['To'], parts['Msg_ID'] = \
                    self._get_msg_anomalia(part)
            # If no rfc822-headers than get info from original daticert.xml
            elif 'report' in parts and 'Msg_ID' not in parts and \
                    'daticert.xml' not in parts and \
                    part.get_content_type() == \
                    'application/xml' and \
                    filename == 'daticert.xml':
                origin_daticert = part.get_payload(decode=True)
                parsed_daticert = self.parse_daticert(cr, uid, origin_daticert)
                if 'recipient_addr' in parsed_daticert:
                    parts['To'] = parsed_daticert['recipient_addr']
                if 'msgid' in parsed_daticert:
                    parts['Msg_ID'] = parsed_daticert['msgid']
            else:
                pass
            # At last, if msg is multipart then call this method iteratively
            if part.is_multipart():
                parts = self._get_msg_payload(cr, uid, part,
                                              parts=parts, num=num + 1)
        return parts
Ejemplo n.º 24
0
 def notification_discount(self, cr, uid, context=None):
     cd_config_obj = self.pool.get('cd.config.settings')
     discount_date = datetime.date.today()+timedelta(days=10)
     promotions_ids = self.search(cr, uid, [('discount_from','=',discount_date),('monitored','=',True),('sequence','=',50)])
     for promotion in self.browse(cr, uid, promotions_ids):
         users_obj = self.pool.get('res.users')
         group_id = self.pool.get('res.groups').search(cr,uid,[('name','=','Trade Marketing Manager')])
         user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
         users = users_obj.browse(cr, uid, user_ids)
         mail_to = ''
         for user in users:
             if user.email and user.email != '':
                 mail_to += user.email+', '
         tms_user = promotion.client_id.section_id.tms_user_id
         if tms_user.email:
             mail_to += tms_user.email
         if mail_to != '':
             create_uid = users_obj.browse(cr, uid, uid)
             cd_config_id = cd_config_obj.search(cr, uid, [])
             cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
             url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
             vals = (discount_date, promotion.client_id.name, url)
             subject = 'Termin obowiązywania rabatu'
             body = decode("Dnia %s zaczyna się termin obowiązywania rabatu dla klienta %s <br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
             self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
             
     discount_date_2 = datetime.date.today()+timedelta(days=2)
     promotions_ids_2 = self.search(cr, uid, [('discount_from','=',discount_date_2),('sequence','=',50)])
     
     for promotion in self.browse(cr, uid, promotions_ids_2):
         users_obj = self.pool.get('res.users')
         group_id = self.pool.get('res.groups').search(cr,uid,[('name','=','Logistics Manager')])
         user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
         users = users_obj.browse(cr, uid, user_ids)
         mail_to = ''
         for user in users:
             if user.email and user.email != '':
                 mail_to += user.email+', '
         if mail_to != '':
             create_uid = users_obj.browse(cr, uid, uid)
             cd_config_id = cd_config_obj.search(cr, uid, [])
             cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
             url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
             subject = 'Termin obowiązywania rabatu'
             
             rows = '<tr><td colspan="2"><b>Produkty akcji promocyjnej:</b></td></tr>'
             l = 0
             for product in promotion.product_rel_ids:
                 l +=1
                 rows += '<tr><td style="width: 20px;">%s.</td><td>%s</td></tr>'%(l, product.product_name)
             
             vals = (discount_date_2, promotion.client_id.name, rows, url)                
             body = decode("Dnia %s zaczyna się termin obowiązywania rabatu dla klienta %s <br/><br/><table>%s</table><br/><a href='%s'>Link do akcji promocyjnej</a>") % vals
             self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
     
     cd_config_id = cd_config_obj.search(cr, uid, [])
     info_guardian = cd_config_obj.browse(cr, uid, cd_config_id[-1]).info_guardian
     discount_date_3 = datetime.date.today()+timedelta(days=info_guardian)
     promotions_ids_3 = self.search(cr, uid, [('discount_from','=',discount_date_3),('sequence','=',50)])
     
     for promotion in self.browse(cr, uid, promotions_ids_3):
         if promotion.client_id.user_id and promotion.client_id.user_id.partner_id.email:
             template = self.pool.get('ir.model.data').get_object(cr, uid, 'cederroth_sale', 'cd_email_template_accept_promo_discount2')
             self.pool.get('email.template').send_mail(cr, uid, template.id, promotion.id, force_send=True, context=context)
     return True
Ejemplo n.º 25
0
 def message_parse(self, cr, uid, message, save_original=False, context=None):
     msg_dict = {
                 'type': 'email',
                 'author_id': False,
             }
     if not isinstance(message, Message):
        if isinstance(message, unicode):
                          
           message = message.encode('utf-8')
        message = email.message_from_string(message)
          
     message_id = message['message-id']
     if not message_id:
                      
        message_id = "<%s@localhost>" % time.time()
        import logging
        # _logger.debug('Parsing Message without message-id, generating a random one: %s', message_id)
     msg_dict['message_id'] = message_id
          
     if message.get('Subject'):
        msg_dict['subject'] = decode(message.get('Subject'))
          
                  
     msg_dict['from'] = decode(message.get('from'))
     msg_dict['to'] = decode(message.get('to'))
     msg_dict['cc'] = decode(message.get('cc'))
          
     if message.get('From'):
        author_ids = self._message_find_partners(cr, uid, message, ['From'], context=context)
        if author_ids:
           msg_dict['author_id'] = author_ids[0]
        msg_dict['email_from'] = decode(message.get('from'))
     partner_ids = self._message_find_partners(cr, uid, message, ['To', 'Cc'], context=context)
     msg_dict['partner_ids'] = [(4, partner_id) for partner_id in partner_ids]
          
     if message.get('Date'):
        try:
           date_hdr = decode(message.get('Date'))
           parsed_date = dateutil.parser.parse(date_hdr, fuzzy=True)
           if parsed_date.utcoffset() is None:
                              
              stored_date = parsed_date.replace(tzinfo=pytz.utc)
           else:
              stored_date = parsed_date.astimezone(tz=pytz.utc)
        except Exception:
              import logging
              #_logger.warning('Failed to parse Date header %r in incoming mail '
              #                       'with message-id %r, assuming current date/time.',
              #                       message.get('Date'), message_id)
              stored_date = datetime.datetime.now()
        msg_dict['date'] = stored_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
          
     if message.get('In-Reply-To'):
        parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', '=', decode(message['In-Reply-To']))])
        if parent_ids:
           msg_dict['parent_id'] = parent_ids[0]
          
     if message.get('References') and 'parent_id' not in msg_dict:
        parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', 'in',
                                                                              [x.strip() for x in decode(message['References']).split()])])
        if parent_ids:
           msg_dict['parent_id'] = parent_ids[0]
     a=[]
     
     string=msg_dict['subject']
     a=string.split(' ')
     res={}
     i=0
     awp=''
     po=''
     po_id=''
     for i in range(len(a)):
         if "AWB" in a[i] :
             awp=a[i]
         if "PO" in a[i]:
             po=a[i]
         po_id=self.pool.get('purchase.order').search(cr,uid,[('name','=',po)])
         
         pur_id=self.pool.get('purchase.order').browse(cr,uid,po_id)
         vals=self.pool.get('purchase.order').write(cr, uid,po_id,{'awb_no':awp})  
     
          
     msg_dict['body'], msg_dict['attachments'] = self._message_extract_payload(cr, uid, message, save_original=save_original)
     return msg_dict
Ejemplo n.º 26
0
    def write(self, cr, uid, ids, vals, context=None):
        users_obj = self.pool.get('res.users')
        promotion = self.browse(cr, uid, ids[0])
        
        if 'discount_from' in vals:
            start_month = datetime.datetime.strptime(vals['discount_from'],"%Y-%m-%d").month
            start_year = datetime.datetime.strptime(vals['discount_from'],"%Y-%m-%d").year
            vals['start_month'] = str(start_month).zfill(2)
            vals['start_year'] = start_year
        
        if 'stage_id' in vals:
            change_stage_id = self.pool.get('cd.promotions.stage').browse(cr, uid, vals['stage_id'])
            current_stage_id = self.browse(cr, uid, ids[0]).stage_id
            
            if change_stage_id.sequence == 50:
                template = self.pool.get('ir.model.data').get_object(cr, uid, 'cederroth_sale', 'email_template_cd_promotion_confirmed')
                self.pool.get('email.template').send_mail(cr, uid, template.id, ids[0], force_send=True, context=context)
       
            
            if change_stage_id.sequence < current_stage_id.sequence and not current_stage_id.sequence < 50:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Status akcji promocyjnej nie może zostać cofnięty'))
            elif current_stage_id.sequence == 10 and change_stage_id.sequence != 20 and change_stage_id.sequence != 90:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Status może zostać zmieniony tylko na "Do akceptacji"'))
            elif current_stage_id.sequence == 20 and change_stage_id.sequence >= 50:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Nie można zmienić na wybrany status'))
            elif current_stage_id.sequence == 20 and change_stage_id.sequence !=10:
                users_obj = self.pool.get('res.users')
                group_id = self.pool.get('res.groups').search(cr,uid,[('name','=','KAM')])
                user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
                if uid in user_ids:
                    raise osv.except_osv(decode('Ostrzeżenie'), decode('Nie można zmienić na wybrany status'))
            elif current_stage_id.sequence == 30 and change_stage_id.sequence not in [10,50,90]:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Status może zostać zmieniony tylko na "W przygotowaniu","Potwierdzona" lub "Anulowano"'))
            elif current_stage_id.sequence == 40 and change_stage_id.sequence not in [10,90]:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Status może zostać zmieniony tylko na "W przygotowaniu" lub "Anulowano"'))
            elif current_stage_id.sequence == 50 and change_stage_id.sequence not in [60,90]:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Status można zmienić tylko na następny'))
            elif current_stage_id.sequence >= 60 and current_stage_id.sequence <= 80 and change_stage_id.sequence - current_stage_id.sequence != 10:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Nie można zmienić na wybrany status'))
            elif current_stage_id.sequence == 80:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Nie można anulować rozliczonej akcji'))
            
            if current_stage_id.sequence == 10 and not promotion.product_rel_ids:
                raise osv.except_osv(decode('Ostrzeżenie'), decode('Do akcji promocyjnej nie zostały dodane produkty')) 
            elif current_stage_id.sequence == 10 and change_stage_id.sequence == 20:
                client = promotion.client_id
                users_obj = self.pool.get('res.users')
                group_obj = self.pool.get('res.groups')
                mail_to = ''
                
                if client.section_id and client.section_id.user_id and client.section_id.user_id.email:
                    mail_to += client.section_id.user_id.email
                
                    if mail_to != '':
                        cd_config_obj = self.pool.get('cd.config.settings')
                        cd_config_id = cd_config_obj.search(cr, uid, [])
                        cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
                        url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
                        vals_email = (url)
                        subject = 'Akcja promocyjna'
                        body = decode("W platformie znajduje się akcja promocyjna do akceptacji <br/><a href='%s'>Link do akcji promocyjnej</a>") % vals_email
                        self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
                        
            elif current_stage_id.sequence == 20 and change_stage_id.sequence == 30:
                #Powiadomienie Country Managera, Dyrektora Finansowego i Dyrektora Handlowego jeżeli rabat pozabudżetowy > 0
                group_obj = self.pool.get('res.groups')
                if promotion.discount_promo_budget > 0:
                    group_id = group_obj.search(cr,uid,[('name','in',['Country Manager','Finances Director','Trade Director'])])
                    user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id),('id','!=',1)])
                    mail_to = ''

                    for user in users_obj.browse(cr, uid, user_ids):
                        if user.email:
                            mail_to += user.email + ', '
                
                    if mail_to != '':
                        cd_config_obj = self.pool.get('cd.config.settings')
                        cd_config_id = cd_config_obj.search(cr, uid, [])
                        cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
                        url = ("http://%s/?db=%s#id=%s&view_type=form&model=cd.promotions")%(cd_crm, cr.dbname, promotion.id)
                        vals_email = (url)
                        subject = 'Akcja promocyjna'
                        body = decode("W platformie znajduje się akcja promocyjna do akceptacji, w której rabat promocyjny został przekroczony.<br/><a href='%s'>Link do akcji promocyjnej</a>") % vals_email
                        self.pool.get('product.product').send_mail(cr, uid, body, subject, mail_to)
                        
                #Powiadomienie Dyrektora Handlowego o akceptacji akcji promocyjnej poniżej progu gp.
                self.send_mail_to_sales_director(cr, uid, promotion.id)
                        
        super(cd_promotions, self).write(cr, uid, ids, vals, context=context)
        return True
Ejemplo n.º 27
0
    def message_parse(self,
                      cr,
                      uid,
                      message,
                      save_original=False,
                      context=None):
        """Parses a string or email.message.Message representing an
           RFC-2822 email, and returns a generic dict holding the
           message details.

           :param message: the message to parse
           :type message: email.message.Message | string | unicode
           :param bool save_original: whether the returned dict
               should include an ``original`` attachment containing
               the source of the message
           :rtype: dict
           :return: A dict with the following structure, where each
                    field may not be present if missing in original
                    message::

                    { 'message_id': msg_id,
                      'subject': subject,
                      'from': from,
                      'to': to,
                      'cc': cc,
                      'body': unified_body,
                      'attachments': [('file1', 'bytes'),
                                      ('file2', 'bytes')}
                    }
        """
        msg_dict = {
            'type': 'email',
        }
        if not isinstance(message, Message):
            if isinstance(message, unicode):
                # Warning: message_from_string doesn't always work correctly on unicode,
                # we must use utf-8 strings here :-(
                message = message.encode('utf-8')
            message = email.message_from_string(message)

        message_id = message['message-id']
        if not message_id:
            # Very unusual situation, be we should be fault-tolerant here
            message_id = "<%s@localhost>" % time.time()
            _logger.debug(
                'Parsing Message without message-id, generating a random one: %s',
                message_id)
        msg_dict['message_id'] = message_id

        if message.get('Subject'):
            msg_dict['subject'] = decode(message.get('Subject'))

        # Envelope fields not stored in mail.message but made available for message_new()
        msg_dict['from'] = decode(message.get('from'))
        msg_dict['to'] = decode(message.get('to'))
        msg_dict['cc'] = decode(message.get('cc'))
        msg_dict['email_from'] = decode(message.get('from'))
        partner_ids = self._message_find_partners(cr,
                                                  uid,
                                                  message, ['To', 'Cc'],
                                                  context=context)
        msg_dict['partner_ids'] = [(4, partner_id)
                                   for partner_id in partner_ids]

        if message.get('Date'):
            try:
                date_hdr = decode(message.get('Date'))
                parsed_date = dateutil.parser.parse(date_hdr, fuzzy=True)
                if parsed_date.utcoffset() is None:
                    # naive datetime, so we arbitrarily decide to make it
                    # UTC, there's no better choice. Should not happen,
                    # as RFC2822 requires timezone offset in Date headers.
                    stored_date = parsed_date.replace(tzinfo=pytz.utc)
                else:
                    stored_date = parsed_date.astimezone(tz=pytz.utc)
            except Exception:
                _logger.warning(
                    'Failed to parse Date header %r in incoming mail '
                    'with message-id %r, assuming current date/time.',
                    message.get('Date'), message_id)
                stored_date = datetime.datetime.now()
            msg_dict['date'] = stored_date.strftime(
                tools.DEFAULT_SERVER_DATETIME_FORMAT)

        if message.get('In-Reply-To'):
            parent_ids = self.pool.get('mail.message').search(
                cr, uid,
                [('message_id', '=', decode(message['In-Reply-To'].strip()))])
            if parent_ids:
                msg_dict['parent_id'] = parent_ids[0]

        if message.get('References') and 'parent_id' not in msg_dict:
            msg_list = mail_header_msgid_re.findall(
                decode(message['References']))
            parent_ids = self.pool.get('mail.message').search(
                cr, uid, [('message_id', 'in', [x.strip() for x in msg_list])])
            if parent_ids:
                msg_dict['parent_id'] = parent_ids[0]

        msg_dict['body'], msg_dict[
            'attachments'] = self._message_extract_payload(
                message, save_original=save_original)

        #need to check why old name stays and why parameter files with date
        '''if msg_dict['attachments']:
            if msg_dict['subject'] and msg_dict['subject'].startswith('Fax an'):
                for attachment in msg_dict['attachments']:
                    attachment = list(attachment)
                    if attachment[0]:
                        # if msg_dict['date']:
                        #     attachment[0] = 'Fax_%s_%s' % datetime.datetime.strftime(datetime.datetime.strptime(msg_dict['date'], '%Y-%m-%d %H:%M:%S'), '%Y%m%d'), attachment[0]
                        # else:
                            attachment[0] = 'Fax_%s' % attachment[0]
                    attachment = tuple(attachment)'''
        return msg_dict
Ejemplo n.º 28
0
    def create(self, cr, uid, data, context=None):
        prod_id = super(product_product, self).create(cr,
                                                      uid,
                                                      data,
                                                      context=context)

        packages = self.pool.get('product.packaging').browse(
            cr, uid, [1, 2, 3, 4])
        #box_id = 0
        #pallet_id = 1
        #for pack in packaages:
        #    if pack.ul.type == "box":
        #        box_id = pack.id
        #    elif pack.ul.type == "pallet":
        #        pallet_id = pack.id
        pallet_id = self.pool.get('product.ul').search(
            cr, uid, [('name', 'ilike', 'Paleta')])
        box_id = self.pool.get('product.ul').search(
            cr, uid, [('name', 'ilike', 'Karton')])

        if box_id:

            vals_box = {'product_id': prod_id, 'ul': box_id[0], 'rows': 1}
            self.pool.get('product.packaging').create(cr,
                                                      uid,
                                                      vals_box,
                                                      context=context)

        if pallet_id:

            vals_pallet = {
                'product_id': prod_id,
                'ul': pallet_id[0],
                'rows': 1
            }
            self.pool.get('product.packaging').create(cr,
                                                      uid,
                                                      vals_pallet,
                                                      context=context)

        if 'product_manager' in data and data['product_manager'] != False:
            user = self.pool.get('res.users').browse(cr, uid,
                                                     data['product_manager'])
            self.message_subscribe(cr,
                                   uid, [prod_id], [user.partner_id.id],
                                   context=context)

        users_obj = self.pool.get('res.users')
        group_id = self.pool.get('res.groups').search(
            cr, uid, [('name', 'in', [
                'KAM', 'Finances', 'Logistics', 'Trade Marketing Specialist',
                'Trade Marketing Manager'
            ])])
        user_ids = users_obj.search(cr, uid, [('groups_id', 'in', group_id),
                                              ('id', '!=', 1)])
        users = users_obj.browse(cr, uid, user_ids)
        mail_to = ''
        for user in users:
            if user.email and user.email != '':
                mail_to += user.email + ', '
        prod = self.browse(cr, uid, prod_id)
        if mail_to != '':
            create_uid = users_obj.browse(cr, uid, uid)
            cd_config_obj = self.pool.get('cd.config.settings')
            cd_config_id = cd_config_obj.search(cr, uid, [])
            if cd_config_id:
                cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
            else:
                raise osv.except_osv(
                    decode('Błąd'),
                    decode('Przed dodaniem produktu należy podać adres CRM.'))
            url = (
                "http://%s/?db=%s#id=%s&view_type=form&model=product.product"
            ) % (cd_crm, cr.dbname, prod_id)
            vals = (prod.name, create_uid.name, url)
            subject = 'Dodano nowy produkt'
            body = decode(
                "Dodano nowy produkt o nazwie: %s<br/>Produkt dodał użytkownik: %s<br/><a href='%s'>Link do produktu</a>"
            ) % vals
            self.send_mail(cr, uid, body, subject, mail_to)

        return prod_id
Ejemplo n.º 29
0
    def _message_extract_payload(self, message, save_original=False):
        """Extract body as HTML and attachments from the mail message"""
        attachments = []
        body = u''
        if save_original:
            attachments.append(('original_email.eml', message.as_string()))

        # Be careful, content-type may contain tricky content like in the
        # following example so test the MIME type with startswith()
        #
        # Content-Type: multipart/related;
        #   boundary="_004_3f1e4da175f349248b8d43cdeb9866f1AMSPR06MB343eurprd06pro_";
        #   type="text/html"
        if not message.is_multipart() or message.get('content-type',
                                                     '').startswith("text/"):
            encoding = message.get_content_charset()
            body = message.get_payload(decode=True)
            body = tools.ustr(body, encoding, errors='replace')
            if message.get_content_type() == 'text/plain':
                # text/plain -> <pre/>
                body = tools.append_content_to_html(u'', body, preserve=True)
        else:
            alternative = False
            mixed = False
            html = u''
            for part in message.walk():
                if part.get_content_type() == 'multipart/alternative':
                    alternative = True
                if part.get_content_type() == 'multipart/mixed':
                    mixed = True
                if part.get_content_maintype() == 'multipart':
                    continue  # skip container
                # part.get_filename returns decoded value if able to decode, coded otherwise.
                # original get_filename is not able to decode iso-8859-1 (for instance).
                # therefore, iso encoded attachements are not able to be decoded properly with get_filename
                # code here partially copy the original get_filename method, but handle more encoding
                filename = part.get_param('filename', None,
                                          'content-disposition')
                if not filename:
                    filename = part.get_param('name', None)
                if filename:
                    if isinstance(filename, tuple):
                        # RFC2231
                        filename = email.utils.collapse_rfc2231_value(
                            filename).strip()
                    else:
                        filename = decode(filename)
                encoding = part.get_content_charset()  # None if attachment

                #TODO : J'ai surchargé cette méthode uniquement pour pouvoir définir un format par défaut pour les mails veant d'Excel sans encodage
                if not encoding:
                    encoding = 'windows-1252'
                print 'encoding 2bis =', encoding, type(encoding)

                # 1) Explicit Attachments -> attachments
                if filename or part.get('content-disposition',
                                        '').strip().startswith('attachment'):
                    attachments.append(
                        (filename
                         or 'attachment', part.get_payload(decode=True)))
                    continue
                # 2) text/plain -> <pre/>
                if part.get_content_type() == 'text/plain' and (not alternative
                                                                or not body):
                    body = tools.append_content_to_html(
                        body,
                        tools.ustr(part.get_payload(decode=True),
                                   encoding,
                                   errors='replace'),
                        preserve=True)
                # 3) text/html -> raw
                elif part.get_content_type() == 'text/html':
                    # mutlipart/alternative have one text and a html part, keep only the second
                    # mixed allows several html parts, append html content
                    append_content = not alternative or (html and mixed)
                    html = tools.ustr(part.get_payload(decode=True),
                                      encoding,
                                      errors='replace')
                    if not append_content:
                        body = html
                    else:
                        body = tools.append_content_to_html(body,
                                                            html,
                                                            plaintext=False)
                # 4) Anything else -> attachment
                else:
                    attachments.append(
                        (filename
                         or 'attachment', part.get_payload(decode=True)))
        return body, attachments
Ejemplo n.º 30
0
    def message_parse(self, cr, uid, message, save_original=False, context=None):
        """Parses a string or email.message.Message representing an
           RFC-2822 email, and returns a generic dict holding the
           message details.

           :param message: the message to parse
           :type message: email.message.Message | string | unicode
           :param bool save_original: whether the returned dict
               should include an ``original`` attachment containing
               the source of the message
           :rtype: dict
           :return: A dict with the following structure, where each
                    field may not be present if missing in original
                    message::

                    { 'message_id': msg_id,
                      'subject': subject,
                      'from': from,
                      'to': to,
                      'cc': cc,
                      'body': unified_body,
                      'attachments': [('file1', 'bytes'),
                                      ('file2', 'bytes')}
                    }
        """
        msg_dict = {
            'type': 'email',
        }
        if not isinstance(message, Message):
            if isinstance(message, unicode):
                # Warning: message_from_string doesn't always work correctly on unicode,
                # we must use utf-8 strings here :-(
                message = message.encode('utf-8')
            message = email.message_from_string(message)

        message_id = message['message-id']
        if not message_id:
            # Very unusual situation, be we should be fault-tolerant here
            message_id = "<%s@localhost>" % time.time()
            _logger.debug('Parsing Message without message-id, generating a random one: %s', message_id)
        msg_dict['message_id'] = message_id

        if message.get('Subject'):
            msg_dict['subject'] = decode(message.get('Subject'))

        # Envelope fields not stored in mail.message but made available for message_new()
        msg_dict['from'] = decode(message.get('from'))
        msg_dict['to'] = decode(message.get('to'))
        msg_dict['cc'] = decode(message.get('cc'))
        msg_dict['email_from'] = decode(message.get('from'))
        partner_ids = self._message_find_partners(cr, uid, message, ['To', 'Cc'], context=context)
        msg_dict['partner_ids'] = [(4, partner_id) for partner_id in partner_ids]

        if message.get('Date'):
            try:
                date_hdr = decode(message.get('Date'))
                parsed_date = dateutil.parser.parse(date_hdr, fuzzy=True)
                if parsed_date.utcoffset() is None:
                    # naive datetime, so we arbitrarily decide to make it
                    # UTC, there's no better choice. Should not happen,
                    # as RFC2822 requires timezone offset in Date headers.
                    stored_date = parsed_date.replace(tzinfo=pytz.utc)
                else:
                    stored_date = parsed_date.astimezone(tz=pytz.utc)
            except Exception:
                _logger.warning('Failed to parse Date header %r in incoming mail '
                                'with message-id %r, assuming current date/time.',
                                message.get('Date'), message_id)
                stored_date = datetime.datetime.now()
            msg_dict['date'] = stored_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)

        if message.get('In-Reply-To'):
            parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', '=', decode(message['In-Reply-To'].strip()))])
            if parent_ids:
                msg_dict['parent_id'] = parent_ids[0]

        if message.get('References') and 'parent_id' not in msg_dict:
            msg_list =  mail_header_msgid_re.findall(decode(message['References']))
            parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', 'in', [x.strip() for x in msg_list])])
            if parent_ids:
                msg_dict['parent_id'] = parent_ids[0]

        msg_dict['body'], msg_dict['attachments'] = self._message_extract_payload(message, save_original=save_original)
        
        #need to check why old name stays and why parameter files with date
        '''if msg_dict['attachments']:
            if msg_dict['subject'] and msg_dict['subject'].startswith('Fax an'):
                for attachment in msg_dict['attachments']:
                    attachment = list(attachment)
                    if attachment[0]:
                        # if msg_dict['date']:
                        #     attachment[0] = 'Fax_%s_%s' % datetime.datetime.strftime(datetime.datetime.strptime(msg_dict['date'], '%Y-%m-%d %H:%M:%S'), '%Y%m%d'), attachment[0]
                        # else:
                            attachment[0] = 'Fax_%s' % attachment[0]
                    attachment = tuple(attachment)'''
        return msg_dict
Ejemplo n.º 31
0
 def user_in_group(self, cr, uid, group_name, context=None):
     users_obj = self.pool.get('res.users')
     group_id = self.pool.get('res.groups').search(cr,uid,[('name','=',group_name)])
     user_ids = users_obj.search(cr,uid,[('groups_id','in',group_id)])
     if uid not in user_ids:
         raise osv.except_osv(decode('Ostrzeżenie'), decode('Operację może wykonać tylko %s')%group_name)
Ejemplo n.º 32
0
 def validation_date(self, cr, uid, start_date, stop_date, context=None):
     start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d").date()
     stop_date = datetime.datetime.strptime(stop_date,"%Y-%m-%d").date()
     if stop_date < start_date:
         raise osv.except_osv(decode('Błąd'), decode('Data końcowa nie może być przed datą początkową !'))
     return True
Ejemplo n.º 33
0
    def _message_extract_payload(self, message, save_original=False):
        """Extract body as HTML and attachments from the mail message"""
        attachments = []
        body = u''
        if save_original:
            attachments.append(('original_email.eml', message.as_string()))

        # Be careful, content-type may contain tricky content like in the
        # following example so test the MIME type with startswith()
        #
        # Content-Type: multipart/related;
        #   boundary="_004_3f1e4da175f349248b8d43cdeb9866f1AMSPR06MB343eurprd06pro_";
        #   type="text/html"
        if not message.is_multipart() or message.get('content-type', '').startswith("text/"):
            encoding = message.get_content_charset()
            body = message.get_payload(decode=True)
            body = tools.ustr(body, encoding, errors='replace')
            if message.get_content_type() == 'text/plain':
                # text/plain -> <pre/>
                body = tools.append_content_to_html(u'', body, preserve=True)
        else:
            alternative = False
            mixed = False
            html = u''
            for part in message.walk():
                if part.get_content_type() == 'multipart/alternative':
                    alternative = True
                if part.get_content_type() == 'multipart/mixed':
                    mixed = True
                if part.get_content_maintype() == 'multipart':
                    continue  # skip container
                # part.get_filename returns decoded value if able to decode, coded otherwise.
                # original get_filename is not able to decode iso-8859-1 (for instance).
                # therefore, iso encoded attachements are not able to be decoded properly with get_filename
                # code here partially copy the original get_filename method, but handle more encoding
                filename=part.get_param('filename', None, 'content-disposition')
                if not filename:
                    filename=part.get_param('name', None)
                if filename:
                    if isinstance(filename, tuple):
                        # RFC2231
                        filename=email.utils.collapse_rfc2231_value(filename).strip()
                    else:
                        filename=decode(filename)
                encoding = part.get_content_charset()  # None if attachment
                # 1) Explicit Attachments -> attachments
                if filename or part.get('content-disposition', '').strip().startswith('attachment'):
                    attachments.append((filename or 'attachment', part.get_payload(decode=True)))
                    continue
                # 2) text/plain -> <pre/>
                if part.get_content_type() == 'text/plain' and (not alternative or not body):
                    body = tools.append_content_to_html(body, tools.ustr(part.get_payload(decode=True),
                                                                         encoding, errors='replace'), preserve=True)
                # 3) text/html -> raw
                elif part.get_content_type() == 'text/html':
                    # mutlipart/alternative have one text and a html part, keep only the second
                    # mixed allows several html parts, append html content
                    append_content = not alternative or (html and mixed)
                    html = tools.ustr(part.get_payload(decode=True), encoding, errors='replace')
                    if not append_content:
                        if body:
                            body = tools.append_content_to_html(body, html, plaintext=False)
                        else:
                            body = html
                    else:
                        body = tools.append_content_to_html(body, html, plaintext=False)
                # 4) Anything else -> attachment
                else:
                    attachments.append((filename or 'attachment', part.get_payload(decode=True)))
        return body, attachments
Ejemplo n.º 34
0
    def send_data_reminder(self, cr, uid):
        users_obj = self.pool.get('res.users')

        cd_config_obj = self.pool.get('cd.config.settings')
        cd_config_id = cd_config_obj.search(cr, uid, [])

        if cd_config_id:
            cd_crm = cd_config_obj.browse(cr, uid, cd_config_id[-1]).cd_crm
        else:
            raise osv.except_osv(
                decode('Błąd'),
                decode('Przed dodaniem produktu należy podać adres CRM.'))
        url = ("http://%s/?db=%s") % (cd_crm, cr.dbname)

        group_id = self.pool.get('res.groups').search(
            cr, uid, [('name', 'in', [
                'Logistics', 'Finances', 'Cederroth Data manager',
                'Sales Manager', 'KAM'
            ])])
        if group_id:
            user_ids = users_obj.search(cr, uid,
                                        [('groups_id', 'in', group_id),
                                         ('id', '!=', 1)])
            users = users_obj.browse(cr, uid, user_ids)
            mail_to = ''

            for user in users:
                if user.email and user.email != '':
                    mail_to += user.email + ', '

            all_product_ids = self.search(cr, uid,
                                          [('product_count', '!=', '100%'),
                                           ('state', '=', 'draft')])
            if mail_to != '':
                create_uid = users_obj.browse(cr, uid, uid)

                vals = (len(all_product_ids), url)
                subject = 'OpenERP - Potrzebne dane produktowe'
                body = decode(
                    "W systemie OpenERP jest %s produktów, które wymagaja uzupelnienia danych.<br/><a href='%s'>Link do systemu</a>"
                ) % vals
                self.send_mail(cr, uid, body, subject, mail_to)

        #wyslac wiadomosci do marketingu
        mail_to = ''
        group_id = self.pool.get('res.groups').search(
            cr, uid, [('name', '=', 'Marketing')])
        if group_id:
            user_ids = users_obj.search(cr, uid,
                                        [('groups_id', 'in', group_id),
                                         ('id', '!=', 1)])

            for user_id in user_ids:
                product_ids = self.search(cr, uid,
                                          [('product_manager', '=', user_id),
                                           ('product_count', '!=', '100%'),
                                           ('state', '=', 'draft')])
                if product_ids:
                    user = users_obj.browse(cr, uid, user_id)
                    vals = (len(product_ids), url)
                    body = decode(
                        "W systemie OpenERP jest %s produktów wymagajacych uzupelnienia przez Ciebie danych.<br/> <a href='%s'>Link do systemu</a>"
                    ) % vals
                    self.send_mail(cr, uid, body, subject, user.email)
        return True