Ejemplo n.º 1
0
def fileSave(request):
    #сохранение файла и ресайз
    #файл изображения вставляется из буфера и передается
    #как текст в base64 закодированном виде
    headerValues = headers.initGlobals(request)
    path = os.path.dirname(os.path.abspath(__file__))
    fileContent = request.POST.get('posted_image', '')
    #получаем из POST координаты квадрата, который будем вырезать из картинки
    x1, y1, x2, y2 = unicodeToInt(request.POST.get('posted_image_x1', 0)), \
                     unicodeToInt(request.POST.get('posted_image_y1', 0)), \
                     unicodeToInt(request.POST.get('posted_image_x2', 0)), \
                     unicodeToInt(request.POST.get('posted_image_y2', 0))

    size_w, size_h = unicodeToInt(request.POST.get(
        'posted_image_size_w',
        0)), unicodeToInt(request.POST.get('posted_image_size_h', 0))
    if fileContent.find('image/png'):
        #уберем артефакт из закодированного файла
        fileContent = fileContent.split('base64,')[1]

        #сохраним файл в базу
        file = PM_Files(projectId=headerValues['CURRENT_PROJECT'],
                        authorId=request.user)
        file.file.save(
            'projects/' + str(int(headerValues['CURRENT_PROJECT'].id)) +
            '/pasted.png', ContentFile(base64.b64decode(fileContent)))

        #откроем картинку для изменений в PIL
        im = Image.open(file.file.path)

        width, height = im.size
        if size_h and size_w and x1:
            k_w, k_h = float(width) / float(size_w), float(height) / float(
                size_h)

            im = im.crop(
                (int(x1 * k_w), int(y1 * k_h), int(x2 * k_w), int(y2 * k_h)))
            # todo: убрать все, что отвечало за обрезку изображения
            outfile = "tracker/media/tmp/cropped.png"
            im.save(outfile, "PNG")
            file.file.delete()
            #сохраняем картинку в базу
            file.file.save(
                'projects/' + str(int(headerValues['CURRENT_PROJECT'].id)) +
                '/cropped.png', ContentFile(open(outfile, 'rb').read()))

        file.save()
        return HttpResponse(
            json.dumps({
                'path':
                str(file.file),
                'fid':
                file.id,
                'type':
                file.type,
                'thumbnail':
                protected(thumbnail(str(file), '200x200'))
                if file.isPicture else ''
            }))
    return HttpResponse(json.dumps({'error': 'PNG expected'}))
Ejemplo n.º 2
0
def releasesResponder(request, activeMenuItem=None):
    from PManager.viewsExt import headers

    headerValues = headers.initGlobals(request)
    user = request.user
    if not user.is_authenticated():
        return HttpResponseRedirect('/')

    if 'action' in request.POST:
        action = request.POST.get('action')
        if action == 'remove':
            id = request.POST.get('id', -1)

            release = Release.objects.get(pk=id)

            if user.get_profile().isManager(release.project):
                release.active = False
                release.save()
                return HttpResponse('ok')


    mprojects = []
    try:
        mprojects = [headerValues["CURRENT_PROJECT"]]
    except Exception:
        pass

    for project in mprojects:
        setattr(project, 'releaseList', project.releases.filter(active=True).order_by('-date'))

    return render(request, 'releases/index.html', {'projects': mprojects, 'pageTitle': u'Версии', 'activeMenuItem': 'releases'})
Ejemplo n.º 3
0
def add_timer(request):
    from PManager.classes.logger.logger import Logger
    import datetime

    if not request.user.is_authenticated:
        return redirect('/')

    headerValues = headers.initGlobals(request)

    userTasks = PM_Task.objects.filter(active=True,
                                       closed=False
                                       # resp=request.user
                                       ).exclude(status__code='not_approved')
    if headerValues['CURRENT_PROJECT']:
        userTasks = userTasks.filter(project=headerValues['CURRENT_PROJECT'])

    seconds = request.POST.get('seconds', 0)
    comment = request.POST.get('comment', '')
    task_id = request.POST.get('task_id', 0)

    if seconds and comment and task_id:
        task = userTasks.get(pk=int(task_id))
        if task:
            if task.canPMUserView(request.user.get_profile()):
                # add timer
                dateEnd = datetime.datetime.now() + datetime.timedelta(
                    seconds=int(seconds))
                timer = PM_Timer(dateEnd=dateEnd,
                                 seconds=seconds,
                                 task=task,
                                 user=request.user,
                                 comment=comment)
                timer.save()
                # add comment
                comment = PM_Task_Message(task=task,
                                          text=str(timer) + '<br />' + comment,
                                          author=request.user,
                                          project=task.project,
                                          hidden_from_clients=True)
                comment.save()
                # add user log
                logger = Logger()
                logger.log(request.user, 'DAILY_TIME', seconds,
                           task.project.id)
                return redirect('/add_timer/?' + 'project=' +
                                str(comment.project.id) + '&text=' +
                                u'Успешно%20добавлено')
            else:
                return HttpResponse('Operation not permitted')

    tasks = []
    for task in userTasks:
        if not task.subTasks.filter(active=True).count():
            tasks.append(task)

    c = RequestContext(request, {'tasks': tasks})

    t = loader.get_template('report/add_timer.html')

    return HttpResponse(t.render(c))
Ejemplo n.º 4
0
def get_head_variables(request):
    currentPath = request.get_full_path()

    result = {
        'main':
        headers.initGlobals(request),
        'user':
        request.user,
        'is_admin':
        request.user.is_superuser,
        'is_staff':
        request.user.is_staff,
        'is_detail_page':
        'detail' in currentPath or 'wiki' in currentPath
        or 'project' in currentPath,
        'referrer':
        request.GET.get('r', None),
        'taskdrafts_cnt':
        draft_cnt(request.user),
        'extends':
        'public/index.html' if request.META.get('HTTP_HOST') == 'opengift.io'
        else 'main/base.html',
        'is_opengift':
        request.META.get('HTTP_HOST') == 'opengift.io'
    }

    if request.user.is_authenticated():
        profile = request.user.get_profile()
        if profile:
            result['account_total'] = profile.account_total
        projects = request.user.get_profile().getProjects(
            only_managed=False, locked=True).order_by('name')
        result['projects'] = []
        for project in projects:
            tasksQty = 0
            if request.user.get_profile().isManager(project):
                tasksQty = project.projectTasks.filter(active=True,
                                                       closed=False).count()
            elif request.user.get_profile().isEmployee(project):
                tasksQty = project.projectTasks.filter(
                    active=True, closed=False, resp=request.user).count()
            setattr(project, 'tasksQty', tasksQty)
            result['projects'].append(project)

    return result
Ejemplo n.º 5
0
 def getResponsibleMenu(request):
     headerValues = headers.initGlobals(request)
     widget_manager = TaskWidgetManager()
     draft_id = request.GET.get('draft_id', None)
     if draft_id:
         from PManager.services.task_drafts import get_draft_by_id
         draft = get_draft_by_id(draft_id, request.user)
         if draft:
             users = draft.users.exclude(id=draft.author_id)
         else:
             users = dict()
     else:
         users = widget_manager.getResponsibleList(request.user, headerValues['CURRENT_PROJECT'])
     c = RequestContext(request, {
         'users': users
         })
     t = loader.get_template('helpers/responsible_menu.html')
     return HttpResponse(t.render(c))
Ejemplo n.º 6
0
    def widgetUpdate(request, widget_name):
        headerValues = headers.initGlobals(request)
        if headerValues['REDIRECT']:
            return redirect(headerValues['REDIRECT'])

        widget = {}
        str = 'widget = widgets.%s' % widget_name
        exec(str)
        widget = widget.widget(request, headerValues, {}, [])
        c = RequestContext(request, {})
        if widget:
            if 'redirect' in widget:
                return HttpResponseRedirect(widget['redirect'])

        c.update({widget_name: widget})
        return HttpResponse(
            loader.get_template("%s/templates/widget.html" %
                                widget_name).render(c))
Ejemplo n.º 7
0
    def creditReport(request):

        filterUser = request.GET.get('user', None)
        filterPayer = request.GET.get('payer', None)
        aFilter = {}
        if filterUser:
            aFilter['user'] = filterUser
        if filterPayer:
            aFilter['payer'] = filterPayer
        from PManager.models import Credit

        if request.user.is_superuser:
            headerValues = headers.initGlobals(request)
            p = headerValues['CURRENT_PROJECT']

            credits = Credit.objects.filter(task__project=p, value__gt=0)
            if aFilter:
                credits = Credit.objects.filter(**aFilter)

            credits = credits.order_by('-pk')
            aCredits = []
            sumCreditUserTo = 0
            sumCreditUserFrom = 0
            for credit in credits:
                if credit.user and credit.user.id:
                    sumCreditUserTo += credit.value
                else:
                    sumCreditUserFrom += credit.value

                aCredits.append(credit)
            payments = Credit.objects.filter(value__lt=0).order_by('-pk')
            c = RequestContext(request, {})
            c.update({
                'credits': aCredits,
                'payments': payments,
                'sumFrom': sumCreditUserFrom,
                'sumManager': sumCreditUserFrom * 0.15,
                'total': (sumCreditUserFrom * 0.85 - sumCreditUserTo),
                'sumTo': sumCreditUserTo
            })
            t = loader.get_template('report/credit_report.html')
            return HttpResponse(t.render(c))
Ejemplo n.º 8
0
def milestonesResponder(request, activeMenuItem=None):
    from PManager.viewsExt import headers

    headerValues = headers.initGlobals(request)
    create_milestone_from_post(request, headerValues)
    user = request.user
    if not user.is_authenticated():
        return HttpResponseRedirect('/')

    context = RequestContext(request)
    selected_project = context.get("CURRENT_PROJECT")
    if selected_project:
        mprojects = (selected_project, )
    else:
        mprojects = context.get("projects")

    return render(
        request, 'milestones/index.html', {
            'm_projects': mprojects,
            'pageTitle': u'Цели',
            'activeMenuItem': activeMenuItem
        })
Ejemplo n.º 9
0
def ajaxFilesResponder(request):
    #ajax-респондер для обработки сигналов
    #от виджета file_list
    import re

    def deleteFile(oFile):
        path = oFile.file.path.encode('utf-8')
        if os.path.isfile(path):
            os.remove(path)
        return oFile.delete()

    headerValues = headers.initGlobals(request)
    sectName = re.sub(' +', ' ', request.POST.get('name', '').strip())
    sectId = request.POST.get('section_id', 0)
    parent = int(request.POST.get('parent', 0))
    action = request.POST.get('action', '')
    if sectId == 'tasks':
        files_from_tasks = True
        sectId = 0
    else:
        files_from_tasks = False
        sectId = int(sectId)

    if request.user.is_authenticated():
        #добавление категории
        if action == 'addCategory' and sectName:
            category = PM_File_Category(name=sectName)
            if parent:
                try:
                    category.parent = PM_File_Category.objects.get(id=parent)
                except PM_File_Category.DoesNotExist:
                    pass

            category.save()
            category.projects.add(headerValues['CURRENT_PROJECT'])

            if category.id:
                return HttpResponse(
                    json.dumps({
                        'success': 'Y',
                        'id': category.id
                    }))

        elif action == 'renameCategory' and sectName and sectId:
            result = {}
            try:
                category = PM_File_Category.objects.get(
                    id=sectId, projects=headerValues['CURRENT_PROJECT'])
                category.name = sectName
                category.save()

                result['success'] = 'Y'
            except PM_File_Category.DoesNotExist():
                result['success'] = 'N'

            return HttpResponse(json.dumps(result))
        #получение списка файлов категории
        elif action == 'getFileList':
            category = None
            if sectId:
                try:
                    category = PM_File_Category.objects.get(
                        pk=sectId, projects=headerValues['CURRENT_PROJECT'])
                except PM_File_Category.DoesNotExist:
                    pass

            files = PM_Files.objects.filter(
                projectId=headerValues['CURRENT_PROJECT']).exclude(
                    is_old_version=True)
            if category:
                files = files.filter(category=category)
            else:
                files = files.filter(category__isnull=True)

            if not files_from_tasks and not category:
                files = files.filter(fileTasks__isnull=True,
                                     msgTasks__isnull=True)

            files = files.order_by('name')

            arFiles = []
            for fileObject in files:
                fileJson = fileObject.getJson()
                fileJson.update({
                    'thumbnail':
                    protected(thumbnail(str(fileObject), '200x200'))
                    if fileObject.isPicture else '',
                    'resolution':
                    '' if fileObject.isPicture else ''
                })
                arFiles.append(fileJson)
            return HttpResponse(json.dumps(arFiles))

        #удаление файлов по массиву ID
        elif action == 'deleteFiles':
            fId = request.POST.getlist('files[]', None)
            if fId:
                print fId
                try:
                    aDeletedFiles = []
                    files = PM_Files.objects.filter(
                        projectId=headerValues['CURRENT_PROJECT'], pk__in=fId)
                    if request.user.get_profile().isManager(
                            headerValues['CURRENT_PROJECT']):
                        for oFile in files:
                            aDeletedFiles.append(oFile.id)
                            deleteFile(oFile)
                        return HttpResponse(json.dumps(aDeletedFiles))

                except PM_Files.DoesNotExist:
                    pass

        #удаление дитректории по ID
        elif action == 'deleteDir':
            iDirId = request.POST.get('dirId', None)

            if iDirId:
                try:
                    dir = PM_File_Category.objects.get(
                        projects=headerValues['CURRENT_PROJECT'], pk=iDirId)
                    if request.user.get_profile().isManager(
                            headerValues['CURRENT_PROJECT']):
                        files = dir.files.all()
                        for file in files:
                            if not file.fileTasks.all():
                                deleteFile(file)
                        dir.delete()
                        return HttpResponse(json.dumps({'success': 'Y'}))

                except PM_File_Category.DoesNotExist:
                    pass

        #перенос файлов в директорию
        elif action == 'replaceFiles':
            iDirId = request.POST.get('section_id', None)
            aFilesId = request.POST.getlist('files[]', None)
            aReplacedFiles = []
            dir = None
            if iDirId:
                try:
                    dir = PM_File_Category.objects.get(
                        projects=headerValues['CURRENT_PROJECT'], pk=iDirId)
                except PM_File_Category.DoesNotExist:
                    pass

            files = PM_Files.objects.filter(
                projectId=headerValues['CURRENT_PROJECT'], pk__in=aFilesId)
            if request.user.get_profile().isManager(
                    headerValues['CURRENT_PROJECT']):
                for oFile in files:
                    oFile.category = dir
                    oFile.save()
                    aReplacedFiles.append(oFile.id)

                return HttpResponse(json.dumps(aReplacedFiles))

        elif action == 'getVersionsList':
            fileId = request.POST.get('file_id', None)
            if request.user.get_profile().isManager(
                    headerValues['CURRENT_PROJECT']):
                try:
                    file = PM_Files.objects.get(
                        pk=fileId, projectId=headerValues['CURRENT_PROJECT'])
                    versions = file.versions.all()
                    aFiles = taskExtensions.getFileList(versions)

                    return HttpResponse(json.dumps(aFiles))
                except PM_Files.DoesNotExist:
                    pass

    return HttpResponse(json.dumps({'success': 'N'}))
Ejemplo n.º 10
0
    def _ajax_upload(self, request, *args, **kwargs):
        if request.method == "POST":
            filename = False
            headerValues = headers.initGlobals(request)
            if request.is_ajax() and False:
                # the file is stored raw in the request
                upload = request
                is_raw = True
                # AJAX Upload will pass the filename in the querystring if it
                # is the "advanced" ajax upload
                try:
                    filename = request.POST['qqfilename']
                except KeyError:
                    return HttpResponseBadRequest("AJAX request not valid")
            # not an ajax upload, so it was the "basic" iframe version with
            # submission via form
            else:
                is_raw = False
                if len(request.FILES) == 1:
                    # FILES is a dictionary in Django but Ajax Upload gives
                    # the uploaded file an ID based on a random number, so it
                    # cannot be guessed here in the code. Rather than editing
                    # Ajax Upload to pass the ID in the querystring, observe
                    # that each upload is a separate request, so FILES should
                    # only have one entry. Thus, we can just grab the first
                    # (and only) value in the dict.
                    upload = request.FILES.values()[0]
                else:
                    raise Http404("Bad Upload")

                if u'qqfilename' in request.POST:
                    filename = request.POST[u'qqfilename']
                else:
                    filesReq = request.FILES.getlist('qqfile')

                    if filesReq:
                        filesReq = filesReq[0]

                        filename = filesReq.name

            if not filename:
                return HttpResponse('Not filename found')

            backend = self.get_backend()

            # custom filename handler
            if u'qqpartindex' not in request.POST or request.POST[
                    u'qqpartindex'] == '0':
                kwargs['first_part'] = True
            else:
                kwargs['first_part'] = False

            filename_origin = filename

            project_id = headerValues['CURRENT_PROJECT'].id if headerValues[
                'CURRENT_PROJECT'] and headerValues[
                    'CURRENT_PROJECT'].id else None
            if project_id:
                backend.UPLOAD_DIR = 'projects/' + str(project_id)

            filename = (backend.update_filename(request, filename, *args, **
                                                kwargs) or filename)

            # save the file

            backend.setup(filename, *args, **kwargs)

            success = backend.upload(upload, filename, is_raw, *args, **kwargs)

            # callback
            extra_context = backend.upload_complete(request, filename, *args,
                                                    **kwargs)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': success, 'filename': filename}
            if extra_context is not None:
                ret_json.update(extra_context)

            if u'qqpartindex' in request.POST and int(
                    request.POST[u'qqpartindex']) == int(
                        request.POST[u'qqtotalparts']) - 1:

                fileNow = PM_Files(projectId=headerValues['CURRENT_PROJECT'],
                                   authorId=request.user,
                                   name=filename_origin)
                try:
                    sId = int(request.POST.get('section_id', 0))
                except ValueError:
                    sId = 0

                version_of = int(request.POST.get('version_of', 0))

                if sId:
                    try:
                        fileNow.category = PM_File_Category.objects.get(pk=sId)
                    except PM_File_Category.DoesNotExist:
                        pass

                fileNow.file.name = os.path.join(ret_json['path'])
                fileNow.save()

                if version_of:
                    try:
                        fileOld = PM_Files.objects.get(pk=int(version_of))
                        fileOld.addNewVersion(fileNow)
                    except PM_Files.DoesNotExist:
                        pass

                ret_json.update({
                    'id':
                    fileNow.id,
                    'name':
                    fileNow.name,
                    'src':
                    fileNow.src,
                    'is_picture':
                    fileNow.isPicture,
                    'type':
                    fileNow.type,
                    'date_create':
                    fileNow.date_create,
                    'size':
                    fileNow.size,
                    'thumbnail':
                    protected(thumbnail(str(fileNow), '167x167'))
                    if fileNow.isPicture else ''
                })
                # although "application/json" is the correct content type, IE throws a fit
            return HttpResponse(json.dumps(ret_json, cls=DjangoJSONEncoder),
                                content_type='text/html; charset=utf-8')

        else:
            response = HttpResponseNotAllowed(['POST'])
            response.write("ERROR: Only POST allowed")
            return response
Ejemplo n.º 11
0
    def setUserOptions(request):
        action = request.POST['action']
        if not request.user.is_authenticated():
            return HttpResponse('')

        curUser = request.user

        response = u''
        if action == 'setRole':
            userId = request.POST['user']
            projectId = int(request.REQUEST.get('roleProject', 0))
            if projectId:
                managedProjects = curUser.get_profile().managedProjects
                for p in managedProjects:
                    if projectId == p.id:
                        roleCode = request.POST.get('role', None)
                        set = int(request.POST.get('set', 0))
                        user = User.objects.get(pk=userId)
                        prof = user.get_profile()

                        if set:
                            prof.setRole(roleCode, p)
                        # else:
                        #     prof.deleteRole(roleCode, p)

                return HttpResponse('ok')

        elif action == 'inviteUser':
            arEmail = request.POST.getlist('email[]', {})

            if arEmail:
                for email in arEmail:
                    roles = request.POST.getlist('roles['+email+'][]', [])

                    if not emailMessage.validateEmail(email):
                        return HttpResponse(u'Email is incorrect')
                    if not roles:
                        return HttpResponse(u'Set the role before inviting')

                    headers = initGlobals(request)
                    p = headers['CURRENT_PROJECT']
                    if request.user.get_profile().isManager(p):
                        if p:
                            user = PM_User.getOrCreateByEmail(email, p, roles.pop(), False)
                            if USE_GIT_MODULE:
                                GitoliteManager.regenerate_access(p)

                            for role in roles:
                                user.get_profile().setRole(p, role)

            return HttpResponse('ok')

        elif action == 'getUsers':
            return userHandlers.getMyTeam(request)

        elif action == 'addSpecialty':
            userId = request.POST['user']
            specialty = request.POST['specialty'].upper()
            user = User.objects.get(pk=userId)
            prof = user.get_profile()
            if specialty in prof.specialties.values_list('name', flat=True):
                return HttpResponse('already has this specialty')
            elif user == curUser or curUser.is_superuser:
                specialty, created = Specialty.objects.get_or_create(name=specialty)
                prof.specialties.add(specialty)
                prof.save()
                return HttpResponse(json.dumps({'id': specialty.id, 'name': specialty.name}))

        elif action == 'deleteSpecialty':
            userId = request.POST['user']
            specialty = request.POST['specialty']
            try:
                specialty = int(specialty)
            except ValueError:
                return HttpResponse('specialtyId expected')
            user = User.objects.get(pk=userId)
            prof = user.get_profile()
            if user == curUser or curUser.is_superuser:
                specialty = Specialty.objects.get(id=specialty)
                prof.specialties.remove(specialty)
                prof.save()
                return HttpResponse('specialty deleted')
Ejemplo n.º 12
0
 def __env(request):
     data = dict()
     data['user'] = request.user
     data['main'] = initGlobals(request)
     return data
Ejemplo n.º 13
0
    def paymentReport(request):
        from PManager.models import PM_Task, Credit, PM_ProjectRoles

        resp_id = request.GET.get('resp', None)
        headerValues = headers.initGlobals(request)
        p = headerValues['CURRENT_PROJECT']
        profile = request.user.get_profile()
        if not profile.isClient(p) and not profile.isManager(p):
            return HttpResponse('')

        clientBet = 0
        try:
            clientRole = PM_ProjectRoles.objects.get(role__code='client',
                                                     project=p)
            client = clientRole.user
            clientBet = client.get_profile().getBet(p)
        except PM_ProjectRoles.DoesNotExist:
            pass

        userBets = {}
        atasks = []
        allsum = {
            'plan_cost': 0.,
            'cost': 0.,
            'plan_payment': 0.,
            'payment': 0.,
            'project_cost': 0.,
            'plan_profit': 0.,
            'profit': 0.
        }

        tasks = PM_Task.objects.filter(active=True,
                                       project=p
                                       # planTime__isnull=False
                                       )
        if resp_id:
            tasks = tasks.filter(resp=resp_id)

        tasks = tasks.order_by('-dateCreate')
        for task in tasks:
            if task.subTasks.filter(active=True).count():
                continue

            if task.resp:
                resp = task.resp
                if resp.id in userBets:
                    userBet = userBets[resp.id]
                else:
                    userBet = resp.get_profile().getBet(p)
                    userBets[resp.id] = userBet

                cost = sum(c.value
                           for c in Credit.objects.filter(user__isnull=False,
                                                          task=task))
                payment = sum(d.value for d in Credit.objects.filter(
                    payer__isnull=False, task=task))

                setattr(task, 'resp', resp)
                planTime = (float(task.planTime) if (task.planTime) else 0)

                setattr(task, 'plan_cost', round(planTime * userBet, 2))
                setattr(task, 'cost', round(cost, 2))
                # setattr(task, 'cost', round(float(task.getAllTime()) * userBet / 3600., 2))

                setattr(task, 'plan_payment', planTime * clientBet)
                setattr(task, 'project_cost', payment * 0.15)
                setattr(task, 'plan_profit',
                        task.plan_payment - task.plan_cost - task.project_cost)

                if task.wasClosed or task.closed or p.id == 34:
                    if not payment and clientRole.payment_type == 'fix':
                        payment = task.cost

                    setattr(task, 'payment', payment)
                    setattr(task, 'profit',
                            task.payment - task.cost - task.project_cost)

                    allsum['payment'] += task.payment
                    allsum['profit'] += task.profit

                allsum['cost'] += task.cost
                allsum['plan_cost'] += task.plan_cost
                allsum['project_cost'] += task.project_cost
                allsum['plan_payment'] += task.plan_payment
                allsum['plan_profit'] += task.plan_profit

                atasks.append(task)

        c = RequestContext(request, {})

        payed = sum(p.value for p in Credit.objects.filter(
            value__lt=0, project=p, payer__isnull=False))
        total = sum(d.value for d in Credit.objects.filter(
            value__gt=0, project=p, payer__isnull=False))

        c.update({
            'is_manager':
            request.user.get_profile().isManager(p),
            'tasks':
            atasks,
            'sum':
            allsum,
            'total':
            total,
            'payed':
            payed,
            'debt':
            allsum['payment'] - payed,
            'credits':
            Credit.objects.filter(project=p, payer__isnull=False)
        })
        t = loader.get_template('report/payment_report.html')
        return HttpResponse(t.render(c))
Ejemplo n.º 14
0
    def indexRender(request,
                    widgetList=None,
                    activeMenuItem=None,
                    widgetParams={},
                    template=None):
        # agents
        from PManager.models import Agent
        from django.db.models import Q
        import datetime
        from PManager.viewsExt.tools import TextFilters
        from django.utils.html import escape
        import urllib

        if activeMenuItem == 'main':
            return HttpResponseRedirect('/pub/')

        cType = 'text/html'
        mimeType = None
        bXls = request.GET.get('xls_output', False)

        agents = Agent.objects.filter(
            Q(
                Q(datetime__lt=datetime.datetime.now())
                | Q(datetime__isnull=True)))
        for agent in agents:
            agent.process()

        headerValues = headers.initGlobals(request)
        if headerValues['REDIRECT']:
            return redirect(headerValues['REDIRECT'])

        # stop timers
        leastHours = datetime.datetime.now() - datetime.timedelta(hours=9)
        for timer in PM_Timer.objects.filter(dateStart__lt=leastHours,
                                             dateEnd__isnull=True):
            timer.delete()

        headerWidgets = []
        widgetsInTabs = []
        c = RequestContext(request, {})
        userTimer = None
        userAchievement = None
        messages = None
        messages_qty = 0
        aMessages = []
        pageTitle = ''

        agreementForApprove = None
        if request.user.is_authenticated():
            messages = PM_Task_Message.objects.filter(
                userTo=request.user, read=False).order_by('-dateCreate')

            taskNumber = int(request.GET.get('number', 0))
            taskId = int(request.GET.get('id', 0))
            projectId = int(request.GET.get('project', 0))

            if projectId:
                if taskId:
                    messages = messages.exclude(task=taskId, project=projectId)
                elif taskNumber:
                    messages = messages.exclude(task__number=taskNumber,
                                                project=projectId)

            messages = messages.exclude(code="WARNING")
            messages_qty = messages.count()

            for mes in messages:
                setattr(mes, 'text',
                        TextFilters.getFormattedText(escape(mes.text)))
                setattr(mes, 'text', TextFilters.convertQuotes(mes.text))
                aMessages.append(mes)

            if not widgetList:
                widgetList = ['tasklist']

            unapprovedAgreements = Agreement.objects.filter(
                payer=request.user, approvedByPayer=False)
            unapprovedAgreementsResp = Agreement.objects.filter(
                resp=request.user, approvedByResp=False)

            if unapprovedAgreements:
                agreementForApprove = unapprovedAgreements[0]
            elif unapprovedAgreementsResp:
                agreementForApprove = unapprovedAgreementsResp[0]

            userTimer = PM_Timer.objects.filter(user=request.user,
                                                dateEnd__isnull=True)
            if userTimer:
                userTimer = userTimer[0]
                timerDataForJson = userTimer.getTime()
                timerDataForJson[
                    'started'] = True if not userTimer.dateEnd else False
                setattr(userTimer, 'jsonData', timerDataForJson)

            arPageParams = {
                'pageCount': 10,
                'page': int(request.POST.get('page', 1))
            }

            for widgetName in widgetList:
                # TODO: change this!!
                str = 'widget = widgets.%s' % widgetName
                exec(str)
                if widgetName == 'tasklist':
                    widget = widget.widget(request, headerValues, widgetParams,
                                           [], arPageParams)
                else:
                    widget = widget.widget(request, headerValues, widgetParams,
                                           [])

                if widget:
                    if 'redirect' in widget:
                        return HttpResponseRedirect(widget['redirect'])
                    if 'title' in widget:
                        pageTitle = widget['title']

                    c.update({widgetName: widget})
                    if bXls:
                        templateName = 'xls'
                    else:
                        templateName = 'widget'

                    widgetHtml = loader.get_template(
                        "%s/templates/%s.html" %
                        (widgetName, templateName)).render(c)

                    if 'tab' in widget and widget['tab']:
                        widgetsInTabs.append({
                            'code': widgetName,
                            'name': widget['name'],
                            'html': widgetHtml
                        })
                    else:
                        headerWidgets.append(widgetHtml)

            if request.is_ajax():
                if request.GET.get('modal', None) is not None:
                    t = loader.get_template('main/xhr_response_modal.html')
                else:
                    t = loader.get_template('main/xhr_response.html')
            else:
                if request.GET.get('frame_mode', False):
                    t = loader.get_template('index_frame.html')
                elif bXls:
                    cType = 'application/xls'
                    mimeType = 'application/xls'
                    t = loader.get_template('index_xls.html')
                elif template == 'new':
                    t = loader.get_template('index_new.html')
                else:
                    t = loader.get_template('index.html')

            c.update({'widget_header': u" ".join(headerWidgets)})
            c.update({'widgets': widgetsInTabs})

            # uAchievement = PM_User_Achievement.objects.filter(user=request.user, read=False)
            # userAchievement = uAchievement[0] if uAchievement and uAchievement[0] else None
            #
            # if userAchievement:
            #     if userAchievement.achievement.delete_on_first_view:
            #         userAchievement.delete()
            #     else:
            #         userAchievement.read = True
            #         userAchievement.save()
        else:
            import re
            # if is not main page
            if re.sub(r'([^/]+)', '', request.get_full_path()) == '/':
                t = loader.get_template(
                    'public/index.html' if request.META['HTTP_HOST'] ==
                    'opengift.io' else 'main/promo.html')
            else:
                return HttpResponseRedirect(
                    '/login/?backurl=' + urllib.quote(request.get_full_path()))

        if not headerValues['FIRST_STEP_FORM']:
            cur_notice = PM_Notice.getForUser(request.user,
                                              request.get_full_path())
            if cur_notice:
                # cur_notice.setRead(request.user)
                c.update({'current_notice': cur_notice})

        c.update({
            'pageTitle':
            pageTitle,
            'activeMenuItem':
            activeMenuItem,
            'userTimer':
            userTimer,
            'currentProject':
            headerValues['CURRENT_PROJECT'],
            # 'userAchievement': userAchievement,
            'messages':
            aMessages,
            'messages_qty':
            messages_qty,
            'agreementForApprove':
            agreementForApprove,
            'activeWidget':
            headerValues['COOKIES']['ACTIVE_WIDGET']
            if 'ACTIVE_WIDGET' in headerValues['COOKIES'] else None
        })

        response = HttpResponse(t.render(c),
                                content_type=cType,
                                mimetype=mimeType)
        if bXls:
            response['Content-Disposition'] = 'attachment; filename="file.xls"'

        for key in headerValues['SET_COOKIE']:
            set_cookie(response, key, headerValues['SET_COOKIE'][key])
        return response