portal_erp.py 22.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
from odoo import fields, http, _
from odoo.http import request
from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager
from odoo.tools import date_utils, groupby as groupbyelem
from odoo.osv.expression import AND
from dateutil.relativedelta import relativedelta
from operator import itemgetter
from collections import OrderedDict
from odoo.exceptions import AccessError, MissingError, UserError
from odoo.addons.portal.controllers.mail import _message_post_helper
from datetime import datetime, timedelta
import json
import base64
import werkzeug
import logging
_logger = logging.getLogger(__name__)
from odoo.addons.sh_all_in_one_helpdesk.controllers.portal import PortalHelpdesk


class PortalHelpdeskMorsaErp(PortalHelpdesk):

    def _prepare_portal_layout_values(self):
        values = super(PortalHelpdesk, self)._prepare_portal_layout_values()
        stage_close = request.env.ref('sh_all_in_one_helpdesk.close_stage').id
        stage_done = request.env.ref('sh_all_in_one_helpdesk.done_stage').id
        stage_cancel = request.env.ref('sh_all_in_one_helpdesk.cancel_stage').id

        ticket_domain = [('stage_id.id','not in',[stage_close,stage_done,stage_cancel])]

        
        if request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'user':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
        elif request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'leader':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
            ticket_domain.append(('team_head', '=', request.env.user.id))
        elif request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'manager':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(('user_id', '=', False))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(('sh_user_ids', '=', False))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
            ticket_domain.append(('team_head', '=', request.env.user.id))
            ticket_domain.append(('team_head', '=', False))
        else:
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))


        new_domain_erp = AND([self.prepare_portal_layout_erp_asistence(), ticket_domain])
        erp_count = len(request.env['helpdesk.ticket'].sudo().search(new_domain_erp))

        tickets = request.env['helpdesk.ticket'].sudo().search(ticket_domain)
        values['tickets'] = tickets
        values['erp_count'] = erp_count
        return values


    def prepare_portal_layout_erp_asistence(self):
        domain = [('team_id.id','=',request.env.ref('helpdesk_morsa.erp_asistense').id)]
        return domain

    @http.route(['/my/erp', '/my/erp/page/<int:page>'],type='http',auth="user",website=True)
    def portal_my_erp(self,ctr='show',page=1,sortby=None,filterby=None,search=None,search_in='all',groupby='create_by',**kw):
        values = self._prepare_portal_layout_values()
        HelpdeskTicket = request.env['helpdesk.ticket'].sudo()
        #domain = self._prepare_portal_layout_erp_asistence()
        searchbar_sortings = {
            'create_date': {
                'label': _('Newest'),
                'order': 'create_date desc'
            },
            'name': {
                'label': _('Name'),
                'order': 'name'
            },
        }
        searchbar_inputs = {
            'all': {
                'input': 'all',
                'label': _('Search in All')
            },
        }

        searchbar_groupby = {
            'create_by': {
                'input': 'create_by',
                'label': _('Created By')
            },
            'ticket_type': {
                'input': 'ticket_type',
                'label': _('Ticket Type')
            },
            'status': {
                'input': 'status',
                'label': _('Status')
            },
            'customer': {
                'input': 'customer',
                'label': _('Customer')
            },
            'category': {
                'input': 'category',
                'label': _('Category')
            },
            'subcategory': {
                'input': 'subcategory',
                'label': _('Sub Category')
            },
            'subject': {
                'input': 'subject',
                'label': _('Subject')
            },
            'priority': {
                'input': 'priority',
                'label': _('Priority')
            },
            'state': {
                'input': 'state',
                'label': _('Reply Status')
            },
        }

        today = fields.Date.today()
        quarter_start, quarter_end = date_utils.get_quarter(today)
        last_week = today + relativedelta(weeks=-1)
        last_month = today + relativedelta(months=-1)
        last_year = today + relativedelta(years=-1)

        searchbar_filters = {
            'all': {
                'label': _('All'),
                'domain': []
            },
            'today': {
                'label': _('Today'),
                'domain': [("create_date", "=", today)]
            },
            'week': {
                'label':
                _('This week'),
                'domain':
                [('create_date', '>=', date_utils.start_of(today, "week")),
                 ('create_date', '<=', date_utils.end_of(today, 'week'))]
            },
            'month': {
                'label':
                _('This month'),
                'domain':
                [('create_date', '>=', date_utils.start_of(today, 'month')),
                 ('create_date', '<=', date_utils.end_of(today, 'month'))]
            },
            'year': {
                'label':
                _('This year'),
                'domain':
                [('create_date', '>=', date_utils.start_of(today, 'year')),
                 ('create_date', '<=', date_utils.end_of(today, 'year'))]
            },
            'quarter': {
                'label':
                _('This Quarter'),
                'domain': [('create_date', '>=', quarter_start),
                           ('create_date', '<=', quarter_end)]
            },
            'last_week': {
                'label':
                _('Last week'),
                'domain':
                [('create_date', '>=', date_utils.start_of(last_week, "week")),
                 ('create_date', '<=', date_utils.end_of(last_week, 'week'))]
            },
            'last_month': {
                'label':
                _('Last month'),
                'domain':
                [('create_date', '>=',
                  date_utils.start_of(last_month, 'month')),
                 ('create_date', '<=', date_utils.end_of(last_month, 'month'))]
            },
            'last_year': {
                'label':
                _('Last year'),
                'domain':
                [('create_date', '>=', date_utils.start_of(last_year, 'year')),
                 ('create_date', '<=', date_utils.end_of(last_year, 'year'))]
            },
        }
        # default sort by value
        if not sortby:
            sortby = 'create_date'
        order = searchbar_sortings[sortby]['order']
        # default filter by value
        if not filterby:
            filterby = 'all'
        domain = AND([searchbar_filters[filterby]['domain']])

        if search and search_in:
            domain = AND([domain, [('name', 'ilike', search)]])
        ticket_domain = self.prepare_portal_layout_erp_asistence()
        if request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'user':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
        elif request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'leader':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
            ticket_domain.append(('team_head', '=', request.env.user.id))
        elif request.env.user.sh_portal_user_access and request.env.user.sh_portal_user_access == 'manager':
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(('sh_user_ids', '=', False))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(('user_id', '=', False))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
            ticket_domain.append(('team_head', '=', request.env.user.id))
            ticket_domain.append(('team_head', '=', False))
        else:
            ticket_domain.append(('|'))
            ticket_domain.append(('|'))
            ticket_domain.append(('user_id', '=', request.env.user.id))
            ticket_domain.append(('sh_user_ids', 'in', [request.env.user.id]))
            ticket_domain.append(
                ('partner_id', '=', request.env.user.partner_id.id))
        stage_close = request.env.ref('sh_all_in_one_helpdesk.close_stage').id
        stage_done = request.env.ref('sh_all_in_one_helpdesk.done_stage').id
        stage_cancel = request.env.ref('sh_all_in_one_helpdesk.cancel_stage').id
        ticket_domain.append(('stage_id.id','not in',[stage_close,stage_done,stage_cancel]))
        domain = AND([domain, ticket_domain])

        # count for pager
        erp_count = len(HelpdeskTicket.search(domain).filtered(lambda h: h.team_id == request.env.ref('helpdesk_morsa.erp_asistense').id))
        # pager
        pager = portal_pager(url="/my/erp",url_args={'sortby': sortby,'search_in': search_in,'search': search,'filterby': filterby},total=erp_count,page=page,step=self._items_per_page)
        if groupby == 'create_by':
            order = "create_uid, %s" % order
        elif groupby == 'ticket_type':
            order = "ticket_type, %s" % order
        elif groupby == 'status':
            order = "stage_id, %s" % order
        elif groupby == 'customer':
            order = "partner_id, %s" % order
        elif groupby == 'category':
            order = "category_id, %s" % order
        elif groupby == 'subcategory':
            order = "sub_category_id, %s" % order
        elif groupby == 'subject':
            order = "subject_id, %s" % order
        elif groupby == 'priority':
            order = "priority, %s" % order
        elif groupby == 'state':
            order = 'state,%s' % order
        
        tickets = HelpdeskTicket.search(domain,order=order,limit=self._items_per_page,offset=pager['offset'])
        
        request.session['my_tickets_history'] = tickets.ids[:100]
        if groupby == 'create_by':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('create_uid'))
            ]
        elif groupby == 'ticket_type':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('ticket_type'))
            ]
        elif groupby == 'status':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('stage_id'))
            ]
        elif groupby == 'customer':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('partner_id'))
            ]
        elif groupby == 'category':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('category_id'))
            ]
        elif groupby == 'subcategory':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('sub_category_id'))
            ]
        elif groupby == 'subject':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('subject_id'))
            ]
        elif groupby == 'priority':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('priority'))
            ]
        elif groupby == 'state':
            grouped_tickets = [
                HelpdeskTicket.concat(*g)
                for k, g in groupbyelem(tickets, itemgetter('state'))
            ]
        # content according to pager and archive selected
        values.update({
            'created':ctr,
            'tickets':tickets,
            'grouped_tickets':grouped_tickets,
            'page_name':'erp',
            'default_url':'/my/erp',
            'erp_count':erp_count,
            'pager':pager,
            'searchbar_sortings':searchbar_sortings,
            'search_in':search_in,
            'sortby':sortby,
            'groupby':groupby,
            'searchbar_inputs':searchbar_inputs,
            'searchbar_groupby':searchbar_groupby,
            'searchbar_filters':OrderedDict(sorted(searchbar_filters.items())),
            'filterby':filterby,
        })

        return request.render("helpdesk_morsa.portal_my_erp",values)
    
    @http.route('/portal-create-ticket-erp',type='http',auth='public',csrf=False)
    def portal_create_ticket_erp(self, **kw):
        try:
            login_user = request.env.user
            if login_user and login_user.login != 'public':
                partner_id = False
                if kw.get('partner_id') and kw.get('partner_id') != '':
                    partner_id = request.env['res.partner'].sudo().search(
                        [('id', '=', int(kw.get('partner_id')))], limit=1)
                else:
                    partner_id = request.env['res.partner'].sudo().search(
                        [('email', '=', kw.get('portal_email'))], limit=1)
                if not partner_id:
                    return json.dumps({"resp":"Error","message":"Colaborador no encontrado, favor de verificar que haya agregado uno existente"}) 
                if partner_id:
                    unvalued_tickets = len(
                        request.env['helpdesk.ticket'].sudo().search([
                            ('stage_id','=',request.env.ref('sh_all_in_one_helpdesk.done_stage').id),
                            ('priority_new','=',False)])
                        )
                    if unvalued_tickets >= 3:
                        return json.dumps({"resp":"Error","message":"Tienes demasiados tickets sin evaluar, favor de evaluarlos"})
                    ticket_dic = {
                        'partner_id': partner_id.id,
                        'ticket_from_portal': True
                    }
                    if kw.get('portal_phone'):
                        partner_id.update({'phone': kw.get('portal_phone')})
                        ticket_dic.update({'mobile_no':kw.get('portal_phone')})
                
                    if kw.get('portal_contact_name'):
                        ticket_dic.update({
                            'person_name':
                            kw.get('portal_contact_name'),
                        })
                    if kw.get('portal_email'):
                        ticket_dic.update({
                            'email': kw.get('portal_email'),
                        })

                    team_id = request.env['helpdesk.team'].sudo().browse(request.env.ref('helpdesk_morsa.erp_asistense').id)
                    if team_id:
                        ticket_dic.update({
                            'team_id': team_id.id,
                            'team_head': team_id.team_head.id,
                        })


                    if kw.get('portal_erp_type'):
                        ticket_dic.update({
                            'erp_type':kw.get('portal_erp_type')
                        })
                        if kw.get('portal_erp_type') == 'soporte':
                            if kw.get('portal_sucursal') and kw.get('portal_sucursal') != 'sucursal':
                                portal_surcusal_id = request.env['warehouse.helpdesk'].sudo().browse(int(kw.get('portal_sucursal')))
                                if portal_surcusal_id:
                                    ticket_dic.update({
                                        'warehouse_id':portal_surcusal_id.id
                                    })
                            
                            if kw.get('portal_module') and kw.get('portal_module') != 'modulo':
                                portal_module_id = request.env['erp.modules'].sudo().browse(int(kw.get('portal_module')))
                                if portal_module_id:
                                    ticket_dic.update({
                                        'erp_id':portal_module_id.id
                                    })
                            else:
                                self.raise_error("Es necesario el apartado de modulo para crear su ticket")

                            
                        elif kw.get('portal_erp_type') == 'mejora':
                            if 'portal_file' not in request.params and  'portal_file_mejora' not in request.params:
                                return json.dumps({"resp":"Error","message":"Es necesario agregar la archivos"})
                        else:
                            return json.dumps({"resp":"Error","message":"El tipo de ticket no se encuentra dentro de los valores"})
                    else:
                        return json.dumps({"resp":"Error","message":"No existe tipo de ticket"})
                   
                    ticket_id = request.env['helpdesk.ticket'].sudo().create(
                        ticket_dic)

                    if 'portal_file' in request.params :
                        attached_files = request.httprequest.files.getlist('portal_file')
                        attachment_ids = []
                        for attachment in attached_files:
                            result = base64.b64encode(attachment.read())
                            attachment_id = request.env['ir.attachment'].sudo(
                            ).create({
                                'name': attachment.filename,
                                'res_model': 'helpdesk.ticket',
                                'res_id': ticket_id.id,
                                'display_name': attachment.filename,
                                'datas': result,
                            })
                            attachment_ids.append(attachment_id.id)
                        ticket_id.attachment_ids = [(6, 0, attachment_ids)]
                    if 'portal_file_mejora' in request.params :
                        attached_files = request.httprequest.files.getlist('portal_file_mejora')
                        attachment_ids = []
                        for attachment in attached_files:
                            result = base64.b64encode(attachment.read())
                            attachment_id = request.env['ir.attachment'].sudo(
                            ).create({
                                'name': attachment.filename,
                                'res_model': 'helpdesk.ticket',
                                'res_id': ticket_id.id,
                                'display_name': attachment.filename,
                                'datas': result,
                            })
                            attachment_ids.append(attachment_id.id)
                        ticket_id.attachment_ids = [(6, 0, attachment_ids)]
            return request.redirect("/my/erp?ctr=False")
        except Exception as e:
            _logger.exception('Something went wrong %s',str(e))

    @http.route(['/my/erp/<int:ticket_id>'],type='http',auth="public",website=True)
    def portal_my_ticket_detail_erp(self,ticket_id,access_token=None,report_type=None,message=False,download=False,**kw):
        try:
            ticket_sudo = self._document_check_access(
                'helpdesk.ticket', ticket_id, access_token=access_token)
        except (AccessError, MissingError):
            return request.redirect('/my')
        if report_type in ('html', 'pdf', 'text'):
            return self._show_report(
                model=ticket_sudo,
                report_type=report_type,
                report_ref=
                'sh_all_in_one_helpdesk.action_portal_report_helpdesk_ticket',
                download=download)
        if ticket_sudo:
            if request.env.company.sh_receive_email_seeing_ticket:
                body = _('Ticket visto por el cliente %s',
                         ticket_sudo.partner_id.name)
                _message_post_helper(
                    "helpdesk.ticket",
                    ticket_sudo.id,
                    body,
                    token=ticket_sudo.access_token,
                    message_type="notification",
                    subtype_xmlid="mail.mt_note",
                    partner_ids=ticket_sudo.user_id.sudo().partner_id.ids,
                )
        values = {
          
            'token': access_token,
            'asistencia': ticket_sudo,
            'message': message,
            'bootstrap_formatting': True,
            'partner_id': ticket_sudo.partner_id.id,
            'report_type': 'html',
        }

        return request.render("helpdesk_morsa.portal_ticket_page_erp",
                              values)