Exemplo n.º 1
0
def postReport(request):
    if request.method == 'POST':
        # print request.POST
        # print request.POST.get('additionalComments')
        categoryObject = Category.objects.get(
            animal_type=request.POST.get('animalType'))
        latitude = request.POST.get('latitude')
        longitude = request.POST.get('longitude')
        mobile_number = request.POST.get('mobileNumber')
        image_path = request.POST.get('imagePath')
        additional_comments = request.POST.get('additionalComments')
        webUrl = (
            "http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s" %
            (latitude, longitude))
        urlstream = urllib2.urlopen(webUrl, timeout=1)
        data = json.loads(urlstream.read())
        location = data['results'][0]["formatted_address"]
        reportObject = Report(animal_type_id=categoryObject.id,
                              latitude=latitude,
                              longitude=longitude,
                              mobile_number=mobile_number,
                              image_path=image_path,
                              location=location,
                              additional_comments=additional_comments)
        reportObject.save()
    return HttpResponse(reportObject.id)
Exemplo n.º 2
0
    def test_parse_report(self):

        response = '''
            {"response":[
                {"clicks":"103","money":"1000.00","day":"2010-10-08","campaign_id":123,"client_id":123,"client_name":"Ford","campaign_name":"Campaign1","ctr":"0.199","impressions":"51635"}
            ]}
            '''
        account = Account.objects.create(remote_id=1)
        Campaign.objects.create(account=account, remote_id=123, fetched=datetime.now())
        Client.objects.create(account=account, remote_id=123, fetched=datetime.now())

        instance = Report(time_from=datetime.now(), time_to=datetime.now())
        instance.parse(json.loads(response)['response'][0])
        instance.save()

        self.assertTrue(isinstance(instance.campaign, Campaign))
        self.assertEqual(instance.campaign.remote_id, 123)

        self.assertTrue(isinstance(instance.client, Client))
        self.assertEqual(instance.client.remote_id, 123)

        self.assertEqual(instance.clicks, 103)
        self.assertEqual(instance.impressions, 51635)
        self.assertEqual(instance.day, date(2010,10,8))
        self.assertEqual(instance.client_name, "Ford")
        self.assertEqual(instance.campaign_name, "Campaign1")
        self.assertEqual(instance.money, '1000.00')
        self.assertEqual(instance.ctr, '0.199')
Exemplo n.º 3
0
def _save_report(report_type, member, team, message):
    standup = team.todays_standup()
    if standup is None:
        standup = Standup(team_id=team.id)
        standup.created_at = datetime.now()
        standup.save()

    report = member.todays_report(standup)
    if report is None:
        report = Report(member_id=member.id, standup_id=standup.id)
        report.created_at = datetime.now()
        report.save()

    if report_type == 'today':
        report.today = message
    elif report_type == 'yesterday':
        report.yesterday = message
    elif report_type == 'problem':
        report.problem = message

    report.updated_at = datetime.now()
    report.save()

    standup.update_at = datetime.now()
    standup.save()

    return 'Rapportert til `{}`'.format(team.name)
Exemplo n.º 4
0
 def test_create_report(self):
     r = Report(author=Account.objects.first(),
                start_period=self.today,
                end_period=self.today,
                scope="maintenance_review")
     r.save()
     self.assertEqual(Report.objects.all().count(), 2)
Exemplo n.º 5
0
    def mutate(self, info, report_data=None):
        report = Report(reported_id_type=report_data.reported_id_type,
                        reported_id=report_data.reported_id,
                        user_id=report_data.user_id,
                        reason=report_data.reason,
                        description=report_data.description)
        report.save()

        return CreateReportMutation(report=report)
Exemplo n.º 6
0
 def test_model_chart(self):
     "Test Chart Model"
     report = Report(name='test')
     report.save()
     obj = Chart(name='test', report=report)
     obj.save()
     self.assertEquals('test', obj.name)
     self.assertNotEquals(obj.id, None)
     obj.delete()
Exemplo n.º 7
0
def user_report(request):
	'''
		report handle
	'''
	if request.method == "POST":
		rep_id = request.POST.get("rep_id","")
		rep_type = request.POST.get("rep_type","")
		reason   = request.POST.get("reason","")
		if rep_id == '' or rep_type == '' or reason == '':
			return HttpResponse(-3)
		report = Report(rep_type=int(rep_type),beReported=rep_id,reason=reason)
		report.save()
		return HttpResponse(0)
Exemplo n.º 8
0
def user_report(request):
    '''
		report handle
	'''
    if request.method == "POST":
        rep_id = request.POST.get("rep_id", "")
        rep_type = request.POST.get("rep_type", "")
        reason = request.POST.get("reason", "")
        if rep_id == '' or rep_type == '' or reason == '':
            return HttpResponse(-3)
        report = Report(rep_type=int(rep_type), beReported=rep_id, reason=reason)
        report.save()
        return HttpResponse(0)
Exemplo n.º 9
0
Arquivo: views.py Projeto: lite/djsite
def addreport(request):
    if request.method == 'POST':
        form = ReportForm(request.POST)
        if form.is_valid():
            report = Report() 
            report.headline = form.cleaned_data.get("headline")
            report.content = form.cleaned_data.get("content")
            report.reporter = request.user.username
            report.date = datetime.now()
            report.save()
            return HttpResponseRedirect(reverse('news:index'))
    else:
        form = ReportForm()

    return render_to_response('news/addreport.html', {'form':form}, context_instance=RequestContext(request))
Exemplo n.º 10
0
def add_report(desc, user_id, user_informed):
    report = Report(description=desc,
                    user=user_id,
                    user_informed=user_informed,
                    status='new',
                    date_created=datetime.datetime.now())
    return report.save()
Exemplo n.º 11
0
def add_report(request):
    """
    Adds a report filled by a user to the site's reports record
    :param request: Request
    :return: HttpResponse
    """
    if request.method == 'POST' and request.is_ajax:
        deq = request.POST.get('description')
        idq = request.POST.get('idq')
        quest = Question.objects.get(id=idq)
        report = Report(report_description=deq)
        report.question = quest
        report.save()
        return HttpResponse("OK")
    else:
        return HttpResponse("Something went wrong")
Exemplo n.º 12
0
 def save_b(self):
     ''' add operation '''
     # entete de la facture
     if not self.table_buy.isvalid:
         return False
     owner = Owner.get(Owner.islog == True)
     date = str(self.date.text())
     values_t = self.table_buy.get_table_items()
     buy = Buy()
     # buy.date = datetime_
     buy.provd_or_clt = \
         ProviderOrClient.get_or_create(
             "Fournisseur", 000000, ProviderOrClient.FSEUR)
     buy.owner = owner
     try:
         buy.save()
         err = False
     except:
         raise
         raise_error("Erreur",
                     u"Impossible d'enregistrer l'entête de la facture")
         return False
     for name, qty, cost_buying, selling_price in values_t:
         rep = Report()
         rep.buy = buy
         rep.type_ = Report.E
         rep.store = 1
         rep.date = date_to_datetime(date)
         rep.product = Product.get(name=name)
         rep.qty = int(qty)
         rep.cost_buying = int(cost_buying)
         rep.selling_price = int(selling_price)
         try:
             rep.save()
         except Exception as e:
             print(e)
             err = True
     if err:
         buy.delete_instance()
         raise_error(
             "Erreur", u"Ce mouvement n'a pas pu etre "
             u"enregistré dans les rapports")
         return False
     else:
         self.parent.Notify(u"L'entrée des articles avec succès", "success")
     self.change_main_context(BuyShowViewWidget, buy=buy)
Exemplo n.º 13
0
Arquivo: buy.py Projeto: Ciwara/GCiss
 def save_b(self):
     ''' add operation '''
     # entete de la facture
     if not self.table_buy.isvalid:
         return False
     owner = Owner.get(Owner.islog == True)
     date = str(self.date.text())
     values_t = self.table_buy.get_table_items()
     buy = Buy()
     # buy.date = datetime_
     buy.provd_or_clt = \
         ProviderOrClient.get_or_create(
             "Fournisseur", 000000, ProviderOrClient.FSEUR)
     buy.owner = owner
     try:
         buy.save()
         err = False
     except:
         raise
         raise_error(
             "Erreur", u"Impossible d'enregistrer l'entête de la facture")
         return False
     for name, qty, cost_buying, selling_price in values_t:
         rep = Report()
         rep.buy = buy
         rep.type_ = Report.E
         rep.store = 1
         rep.date = date_to_datetime(date)
         rep.product = Product.get(name=name)
         rep.qty = int(qty)
         rep.cost_buying = int(cost_buying)
         rep.selling_price = int(selling_price)
         try:
             rep.save()
         except Exception as e:
             print(e)
             err = True
     if err:
         buy.delete_instance()
         raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
                     u"enregistré dans les rapports")
         return False
     else:
         self.parent.Notify(u"L'entrée des articles avec succès", "success")
     self.change_main_context(BuyShowViewWidget, buy=buy)
Exemplo n.º 14
0
def report(request):
    if request.method == 'POST':
        errors = []
        try:
            patientId = int(request.POST.get('patientId'))
            name = request.POST.get('name')
            latitude = float(request.POST.get('latitude'))
            longitude = float(request.POST.get('longitude'))
            dt = request.POST.get('datetime')
            datetime = datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
            incomingReport = Report(patientId=patientId, name=name, \
                    latitude=latitude, longitude=longitude, datetime=datetime)
            incomingReport.save()
            return HttpResponse("Report successfully added to database")
        except ValueError:
            return HttpResponse("Report not added properly")
    else:
        raise Http404
Exemplo n.º 15
0
def autoreport(request):
    """
    Generates a report automatically for a denounced question as repeated in
    an exam
    :param request: Request
    :return: HttpResponse
    """
    if request.method == 'POST' and request.is_ajax:
        txt = Question.objects.get(id=request.POST.get('id1')).question_text
        deq = "Esta pregunta esta duplicada con la pregunta con \"" + txt + \
              "\""
        idq = request.POST.get('id2')
        quest = Question.objects.get(id=idq)
        report = Report(report_description=deq)
        report.question = quest
        report.save()
        return HttpResponse("OK")
    else:
        return HttpResponse("Something went wrong")
Exemplo n.º 16
0
 def post(self):
     """Create new report"""
     student = request.get_json()['student']
     labname = request.get_json()['labname']
     assessmentid = request.get_json()['assessmentid']
     answers = request.get_json()['answers']
     starttime = request.get_json()['starttime']
     endtime = request.get_json()['endtime']
     attempt_num = request.get_json()['attemptNum']
     new_report = Report(student=student,
                         labname=labname,
                         assessmentid=assessmentid,
                         answers=answers,
                         starttime=starttime,
                         endtime=endtime,
                         attempt_num=attempt_num)
     try:
         new_report.save()
     except UniqueViolatedError:
         return jsonify(error=""), 409
     return jsonify(message="ok")
Exemplo n.º 17
0
def log_report(uri, data):
    parts = data.strip().split("&")
    form = {}
    for part in parts:
        if len(part) == 0:
            continue
        key, val = map(urllib.unquote_plus, part.split("="))
        form[key] = form.get(key, '') + val

    r = Report()
    r.uri = uri
    r.additional = form.get('a', '')
    r.site_specific = form.get('site', '')
    r.screen = form.get('s', '')
    r.remote_ip = request.access_route[0]
    r.headers = "\r\n".join(["%s: %s" % x for x in request.headers.to_list()])
    r.url = form.get('u', '')
    r.cookie = form.get('c', '')
    r.useragent = form.get('ua', '')
    r.save()
    logging.error("Logged %s" % r)
Exemplo n.º 18
0
def delete_post(board_name):

    current_user = get_current_user(request)

    board = Board.get(Board.name == board_name)
    form = dict(request.forms)

    if bool(form.get('report')):
        reason = form.get('report')
        report_reasons = loads(config['reports.reasons'])
        if reason not in report_reasons:
            return redirect(f'{basename}/{board_name}/')
        for refnum in list(form)[:-1]:
            report = Report(reason=reason,
                            refnum=refnum,
                            board=board,
                            date=datetime.now().replace(microsecond=0))
            report.save()
    else:
        for refnum in form:
            thread = board.posts.where(Post.refnum == refnum).get()
            if (thread.author == current_user
                    or f':{board_name}:' in current_user.mod):

                remove_textual_refs(board, thread)

                if thread.image: remove_media(thread.image)

                if not thread.is_reply:

                    for reply in board.posts.where(
                            Post.replyrefnum == thread.refnum):

                        if reply.image: remove_media(reply.image)
                        reply.delete_instance()

                thread.delete_instance()
                Report.delete().where(refnum == thread.refnum).execute()

    redirect(f'{basename}/{board_name}/')
Exemplo n.º 19
0
def main():
    # Get current day - 1
    logger.info('Calculating yesterday\'s day')
    yesterday = get_yesterday_date()
    # Get yesterday's measurement
    logger.info(f'Getting measurement for {get_formatted_date(yesterday)}')
    measurement = Measurement.objects(
        created=get_formatted_date(yesterday)).first()
    if measurement is None:
        raise Exception(
            f'Measurement for date={get_formatted_date(yesterday)} was not found'
        )

    # Compute the period for that measurment
    logger.info(f'Calculating period for {get_formatted_date(yesterday)}')
    period = get_period(yesterday)
    # Get the report by period
    logger.info(f'Getting report for {period}')
    report = Report.objects(period=period).first()
    if report is None:
        logger.info(f'Report not found, creating a new report for {period}')
        report = Report(
            period=period,
            values=[],
            user=User.objects(email='*****@*****.**').first())
        report.save()

    logger.info(
        f'Adding a new measurement for {measurement.created} in period {period}'
    )
    report_item = MeasurementValue(sys=measurement.sys,
                                   dia=measurement.dia,
                                   pul=measurement.pul,
                                   date=measurement.created,
                                   ok=measurement.is_ok())
    report.values.append(report_item)
    report.save()
    logger.info('Done')
Exemplo n.º 20
0
def add_report_to_cracker(cracker, client_ip, when=None):
    if when is None:
        when = time.time()

    reports = yield Report.find(
        where=["cracker_id=? AND ip_address=?", cracker.id, client_ip], 
        orderby='latest_report_time ASC'
    )
    if len(reports) == 0:
        report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
        yield report.save()
        cracker.current_reports += 1
        yield report.cracker.set(cracker)
    elif len(reports) == 1:
        report = reports[0]
        # Add second report after 24 hours
        if when > report.latest_report_time + 24*3600:
            report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
            yield report.save()
            yield report.cracker.set(cracker)
    elif len(reports) == 2:
        latest_report = reports[1]
        # Add third report after again 24 hours
        if when > latest_report.latest_report_time + 24*3600:
            report = Report(ip_address=client_ip, first_report_time=when, latest_report_time=when)
            yield report.save()
            yield report.cracker.set(cracker)
    else:
        latest_report = reports[-1]
        latest_report.latest_report_time = when
        yield latest_report.save()
    
    cracker.total_reports += 1
    cracker.latest_time = when
    cracker.resiliency = when - cracker.first_time

    yield cracker.save()
Exemplo n.º 21
0
 def save_b(self):
     ''' add operation '''
     # entete de la facture
     print("save")
     if not self.is_valide():
         return
     invoice_date = unicode(self.invoice_date.text())
     num_invoice = int(self.num_invoice.text())
     invoice_type = self.liste_type_invoice[
         self.box_type_inv.currentIndex()]
     lis_error = []
     invoice = Invoice()
     try:
         self.owner = Owner.get(Owner.islog == True)
     except:
         lis_error.append("Aucun utilisateur est connecté <br/>")
     paid_amount = int(self.table_invoice.paid_amount_field.text())
     try:
         clt = ProviderOrClient.get_or_create(
             self.name_client, int(self.phone.replace(" ", "")),
             ProviderOrClient.CLT)
     except ValueError:
         field_error(self.name_client_field,
                     "Nom, numéro de téléphone du client")
     invoice.number = num_invoice
     invoice.owner = self.owner
     invoice.client = clt
     invoice.location = "Bamako"
     invoice.type_ = invoice_type
     invoice.subject = ""
     invoice.paid_amount = paid_amount
     invoice.tax = False
     try:
         invoice.save()
         if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON:
             Refund(type_=Refund.DT,
                    owner=self.owner,
                    amount=paid_amount,
                    date=date_to_datetime(invoice_date),
                    provider_client=clt,
                    invoice=Invoice.get(number=num_invoice)).save()
     except Exception as e:
         invoice.deletes_data()
         lis_error.append(
             "Erreur sur l'enregistrement d'entête de facture<br/>")
         return False
     # Save invoiceitems
     invoice = Invoice.get(Invoice.number == num_invoice)
     for name, qty, price in self.table_invoice.get_table_items():
         rep = Report()
         product = Product.get(Product.name == name)
         rep.store = 1
         rep.product = product
         rep.invoice = invoice
         rep.type_ = Report.S
         rep.cost_buying = int(product.last_report.cost_buying)
         rep.date = date_to_datetime(invoice_date)
         rep.qty = int(qty)
         rep.selling_price = int(price)
         try:
             rep.save()
         except Exception as e:
             lis_error.append(e)
     if lis_error != []:
         invoice.delete_instance()
         self.parent.Notify(lis_error, "error")
         return False
     else:
         self.parent.Notify("Facture Enregistrée avec succès", "success")
         self.table_invoice._reset()
         try:
             self.parent.open_dialog(ShowInvoiceViewWidget,
                                     modal=True,
                                     opacity=100,
                                     table_p=self,
                                     invoice_num=invoice.number)
         except Exception as e:
             print(e)
Exemplo n.º 22
0
            else:
                value = (s[l / 2 - 1] + s[l / 2]) / 2

        metric['value'] = value

    report = Report(system=system, date=date)

    filename = system_name + "-" + date.strftime("%Y%m%d-%H%M%S") + ".gz"
    str_io = StringIO()
    gz = GzipFile(filename, mode="wb", fileobj=str_io)
    gz.write(reportContents.encode("UTF-8"))
    gz.close()

    # so just compress into a memory buffer and save that.
    report.upload.save(filename, ContentFile(str_io.getvalue()))
    report.save()

    for name in metrics:
        metric = metrics[name]
        description = metric['description']
        units = metric['units']
        value = metric['value']

        storedMetric = Metric(name=name,
                              description=description,
                              units=units,
                              report=report,
                              value=value)
        storedMetric.save()

    return HttpResponse("Report upload succeeded",
Exemplo n.º 23
0
                value = (s[l/2 - 1] + s[l/2]) / 2

        metric['value'] = value

    report = Report(system=system, date=date)
    
    filename = system_name + "-" + date.strftime("%Y%m%d-%H%M%S") + ".gz"
    str_io = StringIO()
    gz = GzipFile(filename, mode="wb", fileobj=str_io)
    gz.write(reportContents.encode("UTF-8"))
    gz.close()

    # so just compress into a memory buffer and save that.
    report.upload.save(filename,
                       ContentFile(str_io.getvalue()))
    report.save()

    
    for name in metrics:
        metric = metrics[name]
        description = metric['description']
        units = metric['units']
        value = metric['value']

        storedMetric = Metric(name=name,
                              description=description,
                              units=units,
                              report=report,
                              value=value)
        storedMetric.save()
Exemplo n.º 24
0
def report_add(request, response_format='html'):
    "Create new report based on user choice"
    if 'report' in request.POST:
        report_id = request.POST['report']
        return HttpResponseRedirect(reverse('reports_report_edit', args=[report_id]))
    # FIRST TIME AN OBJECT IS CHOSEN
    if 'choice' in request.POST:
        form = None
        object = request.POST['choice']
        object = str(
            object.replace("{'object_type': u'", '').replace("'}", ''))
        full_object = object
        object = object.split('.', 3)

        module_name = object[0] + '.' + object[1] + '.' + object[2]
        import_name = object[3]

        module = __import__(
            module_name, globals(), locals(), [import_name], -1)
        classobj = getattr(module, import_name)

        obj = classobj()
        names = obj.get_field_names()

        fields = []
        for name in names:
            fields.append(Field(name=name, display=True))

        model = Model(full_object, fields)

        report = Report()
        report.name = "Untitled {0!s} Report".format((obj._meta.object_name))
        report.model = dumps(model)
        report.creator = request.user.profile
        report.save()

        return HttpResponseRedirect(reverse('reports_report_edit', args=[report.id]))

    # Initial Object Type Choice
    user_modules = [mod.name for mod in request.user.profile.get_perspective().get_modules()]
    modules = [mod.name for mod in Module.objects.all()]

    query = Q(object_type__contains="core")
    for module in modules:
        if module not in user_modules:
            query = query | Q(object_type__contains=module)

    object_types = list(Object.objects.all().exclude(query).values(
        'object_type').distinct().order_by('object_type'))

    object_names = []
    for object_type in object_types:
        module_name = _get_module_name(object_type['object_type'])
        human_type = Object.objects.filter(
            object_type=object_type['object_type'])[0].get_human_type()

        object_names.append("{0!s}: {1!s}".format(module_name, human_type))

    form = ObjChoiceForm(request.user, object_types=object_types, object_names=object_names)

    return render_to_response('reports/report_add', {'form': form}, context_instance=RequestContext(request),
                              response_format=response_format)
Exemplo n.º 25
0
def upload_csv(request, report_id):
    '''
    Take data (a list of payroll object in json format) sent by request.
    Create the Report object with report_id.
    If the report_id already in Report table, send error message.
    Else:
        Create Payroll objects for each object in data.
        Create Payroll_Report.
    '''
    report_count = Report.objects.filter(report_id=report_id).count()
    if report_count == 0: #report with report_id doesn't exist
        data = json.loads(request.body)
        # create a new Report
        new_report = Report(report_id=report_id)
        new_report.save()

        for obj in data:
            temp_date = [int(t) for t in obj['date'].split('/')]
            (day, month, year) = (temp_date[0], temp_date[1],
                                  temp_date[2])
            date = datetime(year=year, month=month, day=day)
            # create a Payroll for the current obj
            payroll = Payroll(date=date,
                              hours_worked=float(obj['hours worked']),
                              employee_id=int(obj['employee id']),
                              job_group=obj['job group'],
                              report_id=report_id)
            # 1 -> 1st half month, 16 -> 2nd half month
            start_day = (1 if day <= 15 else 16) 
            # get the end day of the given month 
            end_day = (15 if day <= 15 else calendar.monthrange(year,
                       month)[1])
            start_date_ts = 10000 * year + 100 * month + start_day

            # group A $20/h, group B $30/h
            if payroll.job_group == 'A':
                amount = 20 * payroll.hours_worked
            else:
                amount = 30 * payroll.hours_worked

            #check if the report with same pay period already existed
            payroll_report = \
                Payroll_Report.objects.filter(employee_id=payroll.employee_id,
                    period_start_date_ts=start_date_ts)

            if not payroll_report:
                # if report does not exists, create a new report
                period = str(start_day) + '/' + str(month) + '/' \
                    + str(year) + ' - ' + str(end_day) + '/' \
                    + str(month) + '/' + str(year)
                payroll_report = \
                    Payroll_Report(employee_id=payroll.employee_id,
                                   period_start_date_ts=start_date_ts,
                                   period=period, amount=amount)
            else:
                # if report exists, increment the amount of money
                payroll_report = payroll_report[0]
                payroll_report.amount += amount
            payroll_report.save()
            payroll.save()
        return HttpResponse(json.dumps({'status': 'success'}))
    else:
        return HttpResponse(json.dumps({'status': 'error',
                            'error_message': 'This report is already been uploaded before'
                            }))
Exemplo n.º 26
0
def cpanel_submit(request):
    # The user adding the request
    user = request.user

    name = request.POST['name']
    phone = request.POST['phone']
    email = request.POST['email']
    type = request.POST['device']
    os = request.POST['os']
    problem = request.POST['problem']
    description = request.POST['description']
    deviceObj = Device()
    report = Report()
    usersWithSameEmail = User.objects.filter(email=email)
    reportUser = User()

    userFound = False
    for u in usersWithSameEmail:
        # If user exists, don't create a new one
        if u.email == email:
            reportUser = u
            userFound = True

    if not userFound:
        reportUser.email = email
        reportUser.username = name
        reportUser.password = '******'
        reportUser.save()

    # Get the devices the user has
    usersDevices = Device.objects.filter(owner=reportUser)

    deviceFound = False
    for d in usersDevices:
        # If the device exists recognize it, and use it
        if d.os == os and d.type == type:
            deviceObj = d
            deviceFound = True

    if not deviceFound:
        # Generate device object
        deviceObj.owner = reportUser
        deviceObj.os = os
        deviceObj.type = type
        deviceObj.save()

    # Generate Report
    report.owner = reportUser
    report.device = deviceObj
    report.description = description
    report.problem = problem
    report.completed = False
    report.save()

    # Generate initial status
    status = Status()
    status.report = report
    # Checked in message
    status.message = 'c'
    status.tech = user
    status.save()

    return cpanel(request, True)
Exemplo n.º 27
0
class ReportsViewsTest(TestCase):
    username = "******"
    password = "******"

    def setUp(self):
        self.group, created = Group.objects.get_or_create(name='test')
        self.user, created = DjangoUser.objects.get_or_create(username=self.username)
        self.user.set_password(self.password)
        self.user.save()
        perspective, created = Perspective.objects.get_or_create(name='default')
        perspective.set_default_user()
        perspective.save()
        ModuleSetting.set('default_perspective', perspective.id)

        self.report = Report(name='test')
        self.report.set_default_user()
        self.report.save()

        self.chart = Chart(name='test_chart', report=self.report)
        self.chart.set_default_user()
        self.chart.save()

    ######################################
    # Testing views when user is logged in
    ######################################
    def test_reports_login(self):
        """Testing /reports/"""
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('reports'))
        self.assertEquals(response.status_code, 200)

    def test_index_login(self):
        "Testing /reports/index/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('reports_index'))
        self.assertEquals(response.status_code, 200)

    def test_index_owned(self):
        "Testing /reports/owned/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('reports_index'))
        self.assertEquals(response.status_code, 200)

    # Charts
    def test_chart_add(self):
        "Testing /reports/chart/add/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('reports_chart_add'))
        self.assertEquals(response.status_code, 200)

    def test_chart_delete_login(self):
        "Testing /reports/chart/delete/<chart_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('reports_chart_delete', args=[self.chart.id]))
        self.assertEquals(response.status_code, 200)

    # Reports
    def test_report_add(self):
        "Testing /reports/report/add/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('reports_report_add'))
        self.assertEquals(response.status_code, 200)

    def test_report_delete_login(self):
        "Testing /reports/report/delete/<report_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('reports_report_delete', args=[self.report.id]))
        self.assertEquals(response.status_code, 200)

    ######################################
    # Testing views when user is not logged in
    ######################################
    def test_reports_out(self):
        "Testing /reports/"
        response = self.client.get(reverse('reports'))
        self.assertRedirects(response, reverse('user_login'))

    def test_index_out(self):
        "Testing /reports/index/"
        response = self.client.get(reverse('reports_index'))
        self.assertRedirects(response, reverse('user_login'))

    def test_index_owned_out(self):
        "Testing /reports/owned/"
        response = self.client.get(reverse('reports_index'))
        self.assertRedirects(response, reverse('user_login'))

    # Charts
    def test_chart_add_out(self):
        "Testing /reports/chart/add/"
        response = self.client.get(reverse('reports_chart_add'))
        self.assertRedirects(response, reverse('user_login'))

    def test_chart_add_typed_out(self):
        "Testing /reports/chart/add/<report_id>"
        response = self.client.get(
            reverse('reports_chart_add', args=[self.report.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_chart_edit_out(self):
        "Testing /reports/chart/edit/<chart_id>"
        response = self.client.get(
            reverse('reports_chart_edit', args=[self.chart.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_chart_delete_out(self):
        "Testing /reports/chart/delete/<chart_id>"
        response = self.client.get(
            reverse('reports_chart_delete', args=[self.chart.id]))
        self.assertRedirects(response, reverse('user_login'))

    # Reports
    def test_report_add_out(self):
        "Testing /reports/report/add/"
        response = self.client.get(reverse('reports_report_add'))
        self.assertRedirects(response, reverse('user_login'))

    def test_report_view_out(self):
        "Testing /reports/report/view/<report_id>"
        response = self.client.get(
            reverse('reports_report_view', args=[self.report.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_report_edit_out(self):
        "Testing /reports/report/edit/<report_id>"
        response = self.client.get(
            reverse('reports_report_edit', args=[self.report.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_report_delete_out(self):
        "Testing /reports/report/delete/<report_id>"
        response = self.client.get(
            reverse('reports_report_delete', args=[self.report.id]))
        self.assertRedirects(response, reverse('user_login'))
Exemplo n.º 28
0
def cpanel_submit(request):
	# The user adding the request
	user = request.user

	name = request.POST['name']
	phone = request.POST['phone']
	email = request.POST['email']
	type = request.POST['device']
	os = request.POST['os']
	problem = request.POST['problem']
	description = request.POST['description']
	deviceObj = Device()
	report = Report()
	usersWithSameEmail = User.objects.filter(email=email)
	reportUser = User()

	userFound = False
	for u in usersWithSameEmail:
		# If user exists, don't create a new one
		if u.email == email:
			reportUser = u
			userFound = True

	if not userFound:
		reportUser.email = email
		reportUser.username = name
		reportUser.password = '******'
		reportUser.save()

	# Get the devices the user has
	usersDevices = Device.objects.filter(owner=reportUser)

	deviceFound = False
	for d in usersDevices:
		# If the device exists recognize it, and use it
		if d.os == os and d.type == type:
			deviceObj = d
			deviceFound = True

	if not deviceFound:
		# Generate device object
		deviceObj.owner = reportUser
		deviceObj.os = os
		deviceObj.type = type
		deviceObj.save()

	# Generate Report
	report.owner = reportUser
	report.device = deviceObj
	report.description = description
	report.problem = problem
	report.completed = False
	report.save()

	# Generate initial status
	status = Status()
	status.report = report
	# Checked in message
	status.message = 'c'
	status.tech = user
	status.save()

	return cpanel(request, True)
Exemplo n.º 29
0
 def test_model_report(self):
     obj = Report(name='test')
     obj.save()
     self.assertEquals('test', obj.name)
     self.assertNotEquals(obj.id, None)
     obj.delete()
Exemplo n.º 30
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        print("save")
        if not self.is_valide():
            return
        invoice_date = unicode(self.invoice_date.text())
        num_invoice = int(self.num_invoice.text())
        invoice_type = self.liste_type_invoice[
            self.box_type_inv.currentIndex()]
        lis_error = []
        invoice = Invoice()
        try:
            self.owner = Owner.get(Owner.islog == True)
        except:
            lis_error.append("Aucun utilisateur est connecté <br/>")
        paid_amount = int(self.table_invoice.paid_amount_field.text())
        try:
            clt = ProviderOrClient.get_or_create(
                self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT)
        except ValueError:
            field_error(
                self.name_client_field, "Nom, numéro de téléphone du client")
        invoice.number = num_invoice
        invoice.owner = self.owner
        invoice.client = clt
        invoice.location = "Bamako"
        invoice.type_ = invoice_type
        invoice.subject = ""
        invoice.paid_amount = paid_amount
        invoice.tax = False
        try:
            invoice.save()
            if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON:
                Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount,
                       date=date_to_datetime(invoice_date), provider_client=clt,
                       invoice=Invoice.get(number=num_invoice)).save()
        except Exception as e:
            invoice.deletes_data()
            lis_error.append(
                "Erreur sur l'enregistrement d'entête de facture<br/>")
            return False
        # Save invoiceitems
        invoice = Invoice.get(Invoice.number == num_invoice)
        for name, qty, price in self.table_invoice.get_table_items():
            rep = Report()
            product = Product.get(Product.name == name)
            rep.store = 1
            rep.product = product
            rep.invoice = invoice
            rep.type_ = Report.S
            rep.cost_buying = int(product.last_report.cost_buying)
            rep.date = date_to_datetime(invoice_date)
            rep.qty = int(qty)
            rep.selling_price = int(price)
            try:
                rep.save()
            except Exception as e:
                lis_error.append(e)
        if lis_error != []:
            invoice.delete_instance()
            self.parent.Notify(lis_error, "error")
            return False
        else:
            self.parent.Notify("Facture Enregistrée avec succès", "success")

            self.change_main_context(ShowInvoiceViewWidget,
                                     invoice_num=invoice.number)
Exemplo n.º 31
0
def default(request):

        applicationFolder = getApplicationFolder()

        #if the request is POST -> file is being uploaded
        if str(request.method).lower() == 'post':
                form = UploadFileForm(request.POST, request.FILES)
                #if there is file for uploading
                if form.is_valid():

                        #uplaod the file on the server
                        tarPath = handle_uploaded_file(request.FILES['file'])

                        reportMetaData = {}

                        #here check it could be zip or tar.gz
                        isTar = (tarPath.endswith('tar.gz') or tarPath.endswith('tgz'))
                        isZip = tarPath.endswith('.zip')

                        #get metadata depending on the archive
                        if isTar:
                                reportMetaData = getReportMetadataTar(tarPath)
                        elif isZip:
                                reportMetaData = getReportMetadataZip(tarPath)
                        
                        #create new Report object set its metadata and save it
                        report = Report()
                        report.username = reportMetaData['user']
                        report.ganga_version = reportMetaData['version']
                        report.job_uuid = reportMetaData['uuid']
                        report.date_uploaded = datetime.now()
                        report.save()

                        #save the report's mon links
                        monlinks = reportMetaData['monlinks']
                        
                        for key, value in monlinks.items():

                                monlink = MonitoringLink()
                                monlink.report = report
                                monlink.monitoring_link_name = key
                                monlink.monitoring_link_path = value            
                                monlink.save()
                        
                        #rename the uploaded file on the server with the report id 
                        if isTar:
                                rename_file(tarPath, report.id, 'tar')

                        elif isZip:
                                rename_file(tarPath, report.id, 'zip')

                        #sets the download path that will be shown to the user
                        serverDownloadPath = os.path.join(settings.SERVER_DOWNLOAD_PATH, str(report.id))

                        community, debug = getCommunityAndDebugMode()[0], getCommunityAndDebugMode()[1]
                        if community == 'CMS' and debug == False :
                                #because for CMS there is different DNS
                                serverDownloadPath = os.path.join(settings_HOST+"cmserrorreports/download", str(report.id))
                        elif community == 'CMS':
                                serverDownloadPath = serverDownloadPath.replace('errorreports', 'cmserrorreports')

                        renderToResponse = render_to_response('%s/upload.html' % applicationFolder, {'form': form, 'path': serverDownloadPath }, context_instance = RequestContext(request))    

                        logServerResponse(str(renderToResponse))

                        return renderToResponse
                        
                else:
                    errors=""
                    for key, value in form.errors.iteritems():
                        errors += str(key) + ": "
                        for i in value:
                            errors += str(i) + ", "
                        errors += "     "
                    return render_to_response('%s/upload.html' % applicationFolder, {'form': form, 'path' : 'invalid form: %s' % errors }, context_instance = RequestContext(request))

        else:
            #user = User.objects.create_user('gosho', '*****@*****.**', 'gosho')
            #user.save()

            form = UploadFileForm()

            return render_to_response('%s/upload.html' % applicationFolder, { 'form' : form, 'path' : 'Method: %s' % request.method }, context_instance = RequestContext(request))