def report_scheduled_job(): consumer_key = settings.CONSUMER_KEY consumer_secret = settings.CONSUMER_SECRET access_token = settings.ACCESS_TOKEN access_secret = settings.ACCESS_SECRET max_tweets = settings.MAX_TWEETS auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) sources = Source.objects.filter(status='ACTIVE', type='TWITTER') for active_source in sources: keywords = active_source.keywords.all() for a_keyword in keywords: query = a_keyword.keyword searched_tweets = [ status for status in tweepy.Cursor(api.search, q=query).items( max_tweets) ] source = Reports_Source.objects.get(code='TWT') for status in searched_tweets: tweet_localcreatedtime = status.created_at + timedelta(hours=7) diff = datetime.now() - tweet_localcreatedtime diff_hours = diff.total_seconds() / 3600 if diff_hours <= 1: note = status.text.translate(non_bmp_map) note = "[{}] {}".format(active_source.disaster, smart_str(note)) new_report = Report(note=note, source=source) new_report.save()
def NewReport(request): if request.method == 'POST': com_name = request.POST.get("com_name") acronym = request.POST.get("acronym") wor_id = request.POST.get("wor_id") creator_id = int(request.POST.get("creator_name")) reviewer_id = int(request.POST.get("reviewer")) time = request.POST.get("start_date") print >> sys.stderr, 'End time: ' + str(time) end_time = request.POST.get("end_date") print >> sys.stderr, 'End time: ' + end_time wapt = bool(request.POST.get("f_wapt")) print >> sys.stderr, 'NewReport ' + str(wapt) new_report = Report(company_name=com_name, comp_acronym=acronym, wor_id=wor_id, creator_name_id=creator_id, reviewer_name_id=reviewer_id, pub_date=time, end_date=end_time, report_wapt=wapt) #if request.POST.get("com_priority") is 'low': #new_report.report_status = False #print >> sys.stderr, 'NewReportx ' + str(new_report.report_status) new_report.save() return redirect("/reports/") else: new_report = 'new report here' reviewer = UserProfile.objects.all() print >> sys.stderr, str(reviewer) form = CveForm() return render(request, 'reports/new_report.html', { 'form' :form, 'reviewer': reviewer })
def report_scheduled_job(): consumer_key = settings.CONSUMER_KEY consumer_secret = settings.CONSUMER_SECRET access_token = settings.ACCESS_TOKEN access_secret = settings.ACCESS_SECRET max_tweets = settings.MAX_TWEETS auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) sources = Source.objects.filter(status='ACTIVE', type='TWITTER') for active_source in sources: keywords = active_source.keywords.all() for a_keyword in keywords: query = a_keyword.keyword searched_tweets = [status for status in tweepy.Cursor(api.search, q=query).items(max_tweets)] source = Reports_Source.objects.get(code='TWT') for status in searched_tweets: tweet_localcreatedtime = status.created_at + timedelta(hours=7) diff = datetime.now() - tweet_localcreatedtime diff_hours = diff.total_seconds() / 3600 if diff_hours <= 1: note = status.text.translate(non_bmp_map) note = "[{}] {}".format(active_source.disaster, smart_str(note)) new_report = Report( note=note, source=source ) new_report.save()
def send(request): # make request # nombre doctor # fecha consulta # nombre paciente # edo paciente # observaciones # sugerencias doc_name = request.POST.get('nombre_dr', "") patient_name = request.POST.get('nombre_pac', "") consult_date = request.POST.get('fecha', "") patient_state = request.POST.get('estado_pac', "") observ = request.POST.get('comentarios', "") suggest = request.POST.get('sugerencias', "") rep = Report(doc_name=doc_name, patient_name=patient_name, consult_date=consult_date, patient_state=patient_state, observ=observ, suggest=suggest) rep.save() url = 'https://android.googleapis.com/gcm/send' headers = { 'Content-Type': 'application/json', 'Authorization': 'key=AIzaSyCH7B7qMMbLnQdj6WG1yuvPp3SlsLHtBds' } payload = { "data": { "fecha": consult_date, "doctor": doc_name, "paciente": patient_name, "observaciones": observ, "sugerencias": suggest }, "registration_ids": [ "APA91bHDXfzISMoo6OfqhhODnU7TeNzqCxeE7lYZHhdI801wazh1e7vbITZVTqwKU5avNW0myInlZW3Aat3S8gzqawN9G5fQEkMVNvqkDHRRYt1IDsFrPuc" ] } try: r = requests.post(url, data=json.dumps(payload)) #r = requests.post(url, headers=headers, data=json.dumps(payload)) except requests.exceptions.ConnectionError: return render(request, 'reports/index.html', { 'error_message': "No hay conexión a internet, intente más tarde", }) else: print >> sys.stderr, "POST request response: ", r.status_code if r.status_code == 200: code = 0 else: code = 1 #print >>sys.stderr, consult_date return HttpResponseRedirect( reverse('reports:results', args=(rep.id, code))) finally: pass
def attach_to_waste_deposit(report: Report) -> None: """ Try to find an existing waste deposit in 5 meters from the new report location to attach report. If close waste deposit does not exist the new one with report`s coordinates will be created. """ waste_deposits = WasteDeposit.objects.all() close_waste_deposit = None for waste_deposit in waste_deposits: distance = geodesic(report.location, waste_deposit.location).meters if distance <= settings.WASTE_DEPOSIT_DISTANCE_IN_METERS: settings.LOGGER.info( f'Attaching report {report.id} to the existing ' f'waste deposit {waste_deposit.id} in {round(distance, ndigits=2)} ' f'meters.' ) close_waste_deposit = waste_deposit break if not close_waste_deposit: settings.LOGGER.info( f'Creating new waste deposit for the report {report.id}.' ) close_waste_deposit = WasteDeposit.objects.create( lat=report.lat, long=report.long ) report.waste_deposit_id = close_waste_deposit report.save()
def test_should_raise_404_if_no_tracker(self): report = Report() report.save() c = Client() response = c.get(self.STATS_PATH) self.assertEqual(response.status_code, 404)
def send(request): # make request # nombre doctor # fecha consulta # nombre paciente # edo paciente # observaciones # sugerencias doc_name = request.POST.get('nombre_dr', "") patient_name = request.POST.get('nombre_pac', "") consult_date = request.POST.get('fecha', "") patient_state = request.POST.get('estado_pac', "") observ = request.POST.get('comentarios', "") suggest = request.POST.get('sugerencias', "") rep = Report(doc_name=doc_name, patient_name=patient_name, consult_date=consult_date, patient_state=patient_state, observ=observ, suggest=suggest) rep.save() url = 'https://android.googleapis.com/gcm/send' headers = {'Content-Type': 'application/json', 'Authorization': 'key=AIzaSyCH7B7qMMbLnQdj6WG1yuvPp3SlsLHtBds'} payload = { "data": { "fecha": consult_date, "doctor": doc_name, "paciente": patient_name, "observaciones": observ, "sugerencias": suggest }, "registration_ids": [ "APA91bHDXfzISMoo6OfqhhODnU7TeNzqCxeE7lYZHhdI801wazh1e7vbITZVTqwKU5avNW0myInlZW3Aat3S8gzqawN9G5fQEkMVNvqkDHRRYt1IDsFrPuc" ] } try: r = requests.post(url, data=json.dumps(payload)) #r = requests.post(url, headers=headers, data=json.dumps(payload)) except requests.exceptions.ConnectionError: return render(request, 'reports/index.html', { 'error_message': "No hay conexión a internet, intente más tarde", }) else: print >>sys.stderr, "POST request response: ", r.status_code if r.status_code == 200: code = 0 else: code = 1 #print >>sys.stderr, consult_date return HttpResponseRedirect(reverse('reports:results', args=(rep.id, code))) finally: pass
def getReport(): today = date.today() delta = datetime.timedelta(days=1) yesterday = today - delta trades = Trade.objects.filter( Q(tradeDate__year=today.year) & Q(tradeDate__month=today.month) & Q(tradeDate__day=today.day) ) for trade in trades: try: new_report = Report.objects.get( Q(symbol=trade.symbol) & Q(reportDate__year=today.year) & Q(reportDate__month=today.month) & Q(reportDate__day=today.day) ) except Report.DoesNotExist: # today's new does not exist try: # get yesterday's old_report = Report.objects.get( Q(symbol=trade.symbol) & Q(reportDate__year=yesterday.year) & Q(reportDate__month=yesterday.month) & Q(reportDate__day=yesterday.day) ) old_report.pk = None old_report.save() # clone a new one new_report = old_report new_report.SOD = new_report.EOD # update SOD except Report.DoesNotExist: # yesterday's old does not exist new_report = Report() new_report.symbol = trade.symbol new_report.reportDate = today # update report if trade.side == "B": total = new_report.buys * new_report.buyAve total += trade.quantity * trade.price # new total new_report.buys += trade.quantity # new buys new_report.buyAve = total / new_report.buys # new buy ave new_report.EOD = new_report.EOD + trade.quantity elif trade.side == "S": total = new_report.sells * new_report.sellAve total += trade.quantity * trade.price # new total new_report.sells += trade.quantity # new sells new_report.sellAve = total / new_report.sells # new sell ave new_report.EOD = new_report.EOD - trade.quantity new_report.save() # save result getPNLs(today) # calculate PNLS getTotal(today) # get summary date
def add_report(request): #the user is able to select multiple files if request.method == 'POST': form = ReportForm(request.POST, request.FILES) creator = request.user name = request.POST.get('name') keyword = request.POST.get('keyword') description = request.POST.get('description') encrypted = True if request.POST.get('encrypted') else False longDescription = request.POST.get('longDescription') private = True if request.POST.get('private') else False ip = get_client_ip(request) file = os.path.join(settings.GEOIP_PATH, 'GeoLiteCity.dat') gi = pygeoip.GeoIP(file) info=gi.record_by_addr(ip) area_code = None city = None country = None if info != None: area_code = info['region_code'] city = info['city'] country = info['country_name'] report = Report(creator_id=creator.id,region_code=area_code,city=city,country=country,keyword=keyword, encrypted=encrypted, name=name, description=description,longDescription=longDescription,private =private) # report.save() # file = File(report=report, path=paths) #pass variables to fields paths = request.FILES.getlist('path') #print(request.FILES) for path in paths: File(report=report, path=path).save() #pass variables to fields return HttpResponseRedirect('/reports/$/') else: # This should never happen return HttpResponse('Improper arrival at add_report, see reports.views')
def post(self, request): serializer = MainReportSerializer(data=request.data) if serializer.is_valid(): data_questions = serializer.data['questions'] data_stats = serializer.data['stats'] report = Report() report.patient = self.request.user report.has_headaches = data_questions['has_headaches'] report.mood_level = data_questions['mood_level'] report.other_diseases = data_questions['other_diseases'] report.save() for group, group_data in data_stats.items(): for data_type, type_data in group_data.items(): for data in type_data: ReportData.objects.save_data( self.request.user, data_type, data['timestamp'], data['value'], group, report ) return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_should_return_stats_with_1_tracker_not_found(self): tracker = Tracker(name='Teemo') tracker.save() report = Report() report.save() c = Client() response = c.get(self.STATS_PATH) self.assertEqual(response.status_code, 200) self.assertContains(response, tracker.name, 1) self.assertEqual(response.context['trackers'][0].name, tracker.name) self.assertEqual(response.context['trackers'][0].count, 0) self.assertEqual(response.context['trackers'][0].score, 0)
def test_button_save_and_exit_redirects_to_correct_view( self, mock_update, mock_get): """ Clicking on `Save and exit` button should update the draft barrier and redirect the user to the draft barrier details view """ mock_update.return_value = Report(self.draft) mock_get.return_value = Report(self.draft) redirect_url = reverse('reports:draft_barrier_details_uuid', kwargs={"barrier_id": self.draft["id"]}) response = self.client.post(self.url, data={"action": "exit"}) self.assertRedirects(response, redirect_url) assert mock_update.called is True
def generate_report(self): self._create_directory() report = Report() report.save() report.report = self._get_report_file(report.id) report.neural_network = self.neural_network report.save()
def test_draft_barriers_returns_correct_html(self, mock_list): mock_list.return_value = (Report(self.draft_barrier(4)), Report(self.draft_barrier(5)),) expected_title = "<title>Market Access - Draft barriers</title>" my_draft_barriers_table = '<table class="standard-table my-draft-barriers">' draft_barrier_row = '<tr class="standard-table__row draft-barrier-item">' expected_row_count = 2 response = self.client.get(self.url) html = response.content.decode('utf8') assert HTTPStatus.OK == response.status_code assert expected_title in html assert my_draft_barriers_table in html row_count = html.count(draft_barrier_row) assert expected_row_count == row_count,\ f'Expected {expected_row_count} least one sector option, got: {row_count}'
def test_report_detail_view_loads_html__with_sections_not_started(self, mock_get): draft = self.draft_barrier(30) url = reverse( "reports:draft_barrier_details_uuid", kwargs={"barrier_id": draft["id"]} ) mock_get.return_value = Report(draft) expected_title = "<title>Market Access - Add - Barrier details</title>" expected_callout_container = '<div class="callout callout--warn callout--with-button">' expected_callout_heading = '<h2 class="callout__heading">Unfinished barrier for</h2>' submit_button = '<input type="submit" value="Submit barrier" class="callout__button">' complete_class = "task-list__item__banner--complete" expected_complete_class_count = 3 response = self.client.get(url) html = response.content.decode("utf8") assert HTTPStatus.OK == response.status_code assert expected_title in html assert expected_callout_container in html assert expected_callout_heading in html assert submit_button not in html completed_count = html.count(complete_class) assert expected_complete_class_count == completed_count,\ f'Expected {expected_complete_class_count} admin areas, got: {completed_count}'
def setUp(self): self.graph = Graph.objects.get(pk=1) self.template = ReportTemplate(name="test", start_date=datetime.now(), frequency="h", last_run=datetime.now(), layout={"hello": "world"}, description="Some", graph=self.graph) self.template.save() self.template_id = self.template.id self.datetime = datetime.now() self.report = Report(date_run=self.datetime, table={"hello": "again"}, template=self.template) self.report.save()
def handle(self, quiet=False, *files, **options): connection = connections[DEFAULT_DB_ALIAS] self.style = no_style() cursor = connection.cursor() # we do all messages in one transaction transaction.commit_unless_managed() transaction.enter_transaction_management() transaction.managed(True) # our current date/time in UTC utc_time = datetime.now(pytz.utc) try: # check our reports sent = Report.check_all(utc_time, quiet) if not quiet: print print "%d reports sent." % sent except Exception as e: traceback.print_exc(e) # one uber commit transaction.commit()
def parse_row_data(self, row): if len(row) != 9: return None print(row) ( _, location, shape, duration, description, latitude, longitude, reported_at, occurred_at, ) = row return Report( occurred_at=self.parse_date(occurred_at), reported_at=self.parse_date(reported_at), location=location, shape=shape, duration=duration, description=description, latitude=self.parse_coord(latitude), longitude=self.parse_coord(longitude), )
def _report_upsert(self): """ Create or update a Report record. """ activity = self.submission.get('esg_activity', None) report_name = activity.activity + ' (by ' + self.agency.acronym_primary + ')' # Update report if self.report is not None: self.report.name = report_name self.report.agency = self.agency self.report.local_identifier = self.submission.get( 'local_identifier', None) self.report.agency_esg_activity = activity self.report.status = self.submission.get('status', None) self.report.decision = self.submission.get('decision', None) self.report.valid_from = self.submission.get('valid_from', None) self.report.valid_to = self.submission.get('valid_to', None) self.report.updated_by = self.user self.report.updated_at = datetime.now() self.report.other_comment = self.submission.get( 'other_comment', None) Report.contributing_agencies.through.objects.all().delete() # Create report else: self.report = Report( name=report_name, agency=self.agency, local_identifier=self.submission.get('local_identifier', None), agency_esg_activity=self.submission.get('esg_activity', None), status=self.submission.get('status', None), decision=self.submission.get('decision', None), valid_from=self.submission.get('valid_from', None), valid_to=self.submission.get('valid_to', None), created_by=self.user, other_comment=self.submission.get('other_comment', None)) # Assign contributing agencies contributing_agencies = self.submission.get('contributing_agencies', []) for contributing_agency in contributing_agencies: self.report.contributing_agencies.add(contributing_agency) self.report.save()
def getTotal(report_date): total = Report() total.symbol = "Total" report_list = Report.objects.filter(Q(reportDate=report_date)) for report in report_list: total.SOD += report.SOD total.buys += report.buys total.sells += report.sells total.grossPNL += report.grossPNL total.unrealizedPNL += report.unrealizedPNL total.fees += report.fees total.netPNL += report.netPNL total.LMV += report.LMV total.SMV += report.SMV total.EOD += report.EOD total.reportDate = report_date total.save()
def test_report_delete(self): report = Report(date_run=datetime.now(), table={"hello": "again"}, template=self.template) report.save() rid = report.id try: r = Report.objects.get(pk=rid) exists = True except ReportTemplate.DoesNotExist: exists = False self.assertTrue(exists) r.delete() try: Report.objects.get(pk=rid) exists = True except Report.DoesNotExist: exists = False self.assertFalse(exists)
class ReportHandler(PatternHandler): """ Handles the initialization of the reporting process. """ pattern = r"^\s*R(eport)?\s*$" report = 0 def help(self): # Create a new report in the DB self.report = Report(identity=self.msg.connection.identity, state=1) self.report.save() logger.debug("New report created") # Send initial response to user self.respond("Hello. Please text a number for the incident you are reporting..." + "1-Verbal Abuse, 2-Physical Abuse, 3-Sexual Assault, 4-Robbery, 5-Rape") def handle(self, text): self.help()
def mutate_and_get_payload(root, info, **kwargs): kwargs = check_kwargs(kwargs, info) projects = kwargs['projects'] del kwargs['projects'] report = Report() report.user_added = info.context.user # Если отчет добавляет ГИП, тогда отчет автоматически становится проверенным. if Project.objects.get(id=projects[0]).gip == info.context.user: report.checked_by = info.context.user report.time_checked = timezone.now() # Добавляем к полям модели полученные значения. # "keys" - это глобальный список внешних ключей (имен полей). [ setattr(report, f + '_id' if f in keys else f, kwargs.get(f)) for f in kwargs.keys() ] report.save() projects_states = Project.objects.filter(id__in=projects).values( 'id', 'state_id') for ps in projects_states: ProjectState.objects.create(project_id=ps['id'], state_id=ps['state_id'], report_id=report.id) return CreateReport(report=report)
def test_wetmill(self): self.season = self.rwanda_2010 self.report = Report.get_for_wetmill_season(self.nasho, self.season, self.viewer) self.scorecard = Scorecard.get_for_wetmill_season( self.nasho, self.season, self.viewer) # login with view report permission user self.login(self.viewer) response = self.client.get( reverse('public-wetmill', args=[self.nasho.id])) # nasho should be in the response self.assertContains(response, "Nasho") # check if the finalized report is inside the finalized list of report within the context # shouldn't be. self.assertFalse(self.report in response.context['finalized_reports']) self.assertFalse( self.report in response.context['finalized_scorecards']) # finalize on of this wetmills reports self.report.is_finalized = True self.report.save() # finalize the scorecard for this wetmill self.scorecard.is_finalized = True self.scorecard.save() response = self.client.get( reverse('public-wetmill', args=[self.nasho.id])) # nasho should be in the response self.assertContains(response, "Nasho") # check if the finalized report is inside the finalized list of report within the context self.assertTrue(self.report in response.context['finalized_reports']) self.assertTrue( self.scorecard in response.context['finalized_scorecards']) self.assertIsNone(response.context['last_scorecard']) self.assertIsNone(response.context['last_report']) # finalize the season self.season.is_finalized = True self.season.save() # get the page again response = self.client.get( reverse('public-wetmill', args=[self.nasho.id])) self.assertTrue(self.report in response.context['finalized_reports']) self.assertTrue( self.scorecard in response.context['finalized_scorecards']) self.assertEquals(self.scorecard, response.context['last_scorecard']) self.assertEquals(self.report, response.context['last_report'])
def test_report_detail_view_loads_correct_template(self, mock_get): draft = self.draft_barrier(1) mock_get.return_value = Report(draft) url = reverse('reports:draft_barrier_details_uuid', kwargs={"barrier_id": draft["id"]}) response = self.client.get(url) assert HTTPStatus.OK == response.status_code self.assertTemplateUsed(response, "reports/report_detail.html")
def help(self): # Create a new report in the DB self.report = Report(identity=self.msg.connection.identity, state=1) self.report.save() logger.debug("New report created") # Send initial response to user self.respond("Hello. Please text a number for the incident you are reporting..." + "1-Verbal Abuse, 2-Physical Abuse, 3-Sexual Assault, 4-Robbery, 5-Rape")
def test_delete_report_view_loads_correct_template(self, mock_delete, mock_get, _mock_list): mock_get.return_value = Report(self.draft) redirect_url = reverse("reports:draft_barriers") response = self.client.post(self.url, {}) self.assertRedirects(response, redirect_url) assert mock_get.called is True assert mock_delete.called is True
class ReportTest(TestCase): fixtures = ["schemas.json", "graphs.json", "queries.json", "reports.json"] def setUp(self): self.graph = Graph.objects.get(pk=1) self.template = ReportTemplate(name="test", start_date=datetime.now(), frequency="h", last_run=datetime.now(), layout={"hello": "world"}, description="Some", graph=self.graph) self.template.save() self.template_id = self.template.id self.datetime = datetime.now() self.report = Report(date_run=self.datetime, table={"hello": "again"}, template=self.template) self.report.save() def test_report_creation(self): self.assertIsNotNone(self.report) self.assertEqual(self.report.date_run, self.datetime) def test_report_delete(self): report = Report(date_run=datetime.now(), table={"hello": "again"}, template=self.template) report.save() rid = report.id try: r = Report.objects.get(pk=rid) exists = True except ReportTemplate.DoesNotExist: exists = False self.assertTrue(exists) r.delete() try: Report.objects.get(pk=rid) exists = True except Report.DoesNotExist: exists = False self.assertFalse(exists)
def setUp(self): super(PDFTestCase, self).setUp() self.report = Report.get_for_wetmill_season(self.nasho, self.rwanda_2010, self.admin) self.report.farmers = 100 self.report.capacity = Decimal("10000") self.report.save() self.season = self.rwanda_2010 self.nasho.set_csp_for_season(self.season, self.rtc)
def test_button_save_and_exit_redirects_to_correct_view( self, mock_create, mock_get): """ Clicking on `Save and exit` button should create a draft barrier and redirect the user to the draft barrier details view """ field_name = 'trade_direction' export = "1" draft_barrier = self.draft_barrier(2) mock_create.return_value = Report(draft_barrier) mock_get.return_value = Report(draft_barrier) redirect_url = reverse('reports:draft_barrier_details_uuid', kwargs={"barrier_id": draft_barrier["id"]}) payload = {field_name: export, "action": "exit"} response = self.client.post(self.url, data=payload) self.assertRedirects(response, redirect_url) assert mock_create.called is True
class ReportTest(TestCase): fixtures = ["schemas.json", "graphs.json", "queries.json", "reports.json"] def setUp(self): self.graph = Graph.objects.get(pk=1) self.template = ReportTemplate( name="test", start_date=datetime.now(), frequency="h", last_run=datetime.now(), layout={"hello": "world"}, description="Some", graph=self.graph, ) self.template.save() self.template_id = self.template.id self.datetime = datetime.now() self.report = Report(date_run=self.datetime, table={"hello": "again"}, template=self.template) self.report.save() def test_report_creation(self): self.assertIsNotNone(self.report) self.assertEqual(self.report.date_run, self.datetime) def test_report_delete(self): report = Report(date_run=datetime.now(), table={"hello": "again"}, template=self.template) report.save() rid = report.id try: r = Report.objects.get(pk=rid) exists = True except ReportTemplate.DoesNotExist: exists = False self.assertTrue(exists) r.delete() try: Report.objects.get(pk=rid) exists = True except Report.DoesNotExist: exists = False self.assertFalse(exists)
def handle(self, *args, **options): report = Report( title='Test runner from CLI', description='Test runner from CLI', runner=options['runner'], frequency='on_demand') if 'attributes' in options: report.attributes = options['attributes'] report.save() run = report.run() self.stdout.write(run.result) run.delete() report.delete()
def test_saving_location_redirects_to_correct_view(self, mock_create): draft_barrier = self.draft_barrier(2) mock_create.return_value = Report(draft_barrier) field_name = "location" fiji_uuid = "d9f682ac-5d95-e211-a939-e4115bead28a" redirect_url = reverse("reports:barrier_trade_direction") response = self.client.post(self.url, data={field_name: fiji_uuid}) self.assertRedirects(response, redirect_url) assert mock_create.called is False
def test_trading_bloc_location_saved_in_session(self, mock_create): draft_barrier = self.draft_barrier(2) mock_create.return_value = Report(draft_barrier) session_key = "draft_barrier__location_form_data" expected_form_data = {"country": None, "trading_bloc": "TB00016"} response = self.client.post(self.url, data={"location": "TB00016"}, follow=True) saved_form_data = self.client.session.get(session_key) assert HTTPStatus.OK == response.status_code assert expected_form_data == saved_form_data assert mock_create.called is False
def test_button_continue_redirects_to_correct_view(self, mock_create): """ Clicking on `Continue` button should proceed to trade directions without saving the barrier """ draft_barrier = self.draft_barrier(2) mock_create.return_value = Report(draft_barrier) redirect_url = reverse("reports:barrier_trade_direction") response = self.client.post(self.url, data={}) self.assertRedirects(response, redirect_url) assert mock_create.called is False
def test_saving_location_with_trading_bloc_redirects_to_correct_view( self, mock_create): draft_barrier = self.draft_barrier(2) mock_create.return_value = Report(draft_barrier) field_name = "location" france_uuid = "82756b9a-5d95-e211-a939-e4115bead28a" redirect_url = reverse("reports:barrier_caused_by_trading_bloc") response = self.client.post(self.url, data={field_name: france_uuid}) self.assertRedirects(response, redirect_url) assert mock_create.called is False
def get_queryset(self, *args, **kwargs): """ Only admins of the board can see the reports. """ current_user = self.request.user boards_slug = self.request.GET.get('boards_slug', '') board = Board.objects.get(slug=boards_slug) if board: if current_user in board.admins.all(): queryset_list = Report.get_reports(boards_slug) return queryset_list return []
def test_save_and_continue_redirects_to_correct_view( self, mock_update, mock_get, mock_submit): """ Clicking on `Save and continue` button should update the draft barrier and redirect the user to the draft barrier details view """ mock_update.return_value = Report(self.draft) mock_get.return_value = Report(self.draft) redirect_url = reverse("barriers:barrier_detail", kwargs={"barrier_id": self.draft["id"]}) data = { "summary": "wibble wobble", "is_summary_sensitive": "no", "next_steps_summary": "step 1 - wobble, step 2 - wibble", } response = self.client.post(self.url, data) self.assertRedirects(response, redirect_url) assert mock_update.called is True assert mock_submit.called is True
def test_save_and_continue_redirects_to_correct_view(self, mock_update): """ Clicking on `Save and continue` should take the user to the .../problem/ page """ mock_update.return_value = Report(self.draft) redirect_url = reverse('reports:barrier_about_uuid', kwargs={"barrier_id": self.draft["id"]}) response = self.client.post(self.url, data={}) self.assertRedirects(response, redirect_url) assert mock_update.called is True
def form_valid(self, form): report_query = self.get_report_query(form) report_dict = self.get_report_dict(form) reports = Report.objects.filter(**report_query) if reports.filter(status=ReportStatus.Ready).exists(): report = reports.filter(status=ReportStatus.Ready)[0] messages.add_message(self.request, messages.INFO, u'Отчёт уже построен') return HttpResponseRedirect(report.get_absolute_url()) elif reports.filter(status=ReportStatus.Pending).exists(): return self.render_to_response({ 'form': form, 'pending': reports[0] }) else: report = Report(**report_dict) report.save() try: report.process() #.delay(report) except ConnectionError: return self.render_to_response({ 'form': form, 'error': u'Нет соединения с очередью задач' }) return HttpResponseRedirect(report.get_absolute_url())
def newReport(account, symbol, today): try: mainAccount = account[:5] new_report = Report.objects.get(Q(account=mainAccount) & Q(symbol=symbol) & Q(reportDate=today)) except Report.DoesNotExist: # today's new does not exist new_report = Report() new_report.account = mainAccount new_report.symbol = symbol new_report.reportDate = today new_report.save() #new_report = Report.objects.create(symbol=symbol, reportDate=today) return new_report
def submit(request): if not request.GET.has_key("imei"): return HttpResponse("Expected additional parameters") imei = request.GET["imei"] nmea_str = request.GET["rmc"] nmea_list = nmea_str.split(",") # Sanav sentence is of type GPRMC with a couple extra attributes for voltage and report type # imei - first parameter before sentence, provides a unique id for the device # NMEA type - $GPRMC # UTC time - 095838.000 hhmmss.sss # Status - A # Lat - 2458.9733 ddmm.mmmm Degree Decimal Minute # Lat dir - N # Lon - 12125.6583 ddmm.mmmm Degree Decimal Minute # Lon dir - E # Speed knots - 0.41 # Course - 79.21 # UTC Date - 220905 ddmmyy # Mag. deviation - blank # Checksum - *30 # Voltage - 3777mv # Report type - POLL rep_time = nmea_list[1] rep_lat = nmea_list[3] rep_lat_dir = nmea_list[4] rep_lon = nmea_list[5] rep_lon_dir = nmea_list[6] rep_date = nmea_list[9] r = Report() r.imei = imei r.nmea_type = nmea_list[0][1:] r.status = nmea_list[2] r.speed = nmea_list[7] r.course = nmea_list[8] r.voltage = nmea_list[12][0:-2] r.rep_type = nmea_list[13] r.nmea_sentence = nmea_str # parse and build location lon_dd = float(rep_lon[:-7]) + float(rep_lon[-7:]) / 60.0 if rep_lon_dir == "W": lon_dd *= -1 lat_dd = float(rep_lat[:-7]) + float(rep_lat[-7:]) / 60.0 if rep_lat_dir == "S": lat_dd *= -1 r.loc = Point(lon_dd, lat_dd) # parse and build timestamp year = int(rep_date[4:6]) month = int(rep_date[2:4]) day = int(rep_date[0:2]) hour = int(rep_time[0:2]) minute = int(rep_time[2:4]) sec = int(rep_time[4:6]) ms = int(rep_time[7:]) r.timestamp = datetime.datetime(year, month, day, hour, minute, sec, ms) r.save() return HttpResponse("Report logged")
def process_element(elem): report = Report() print elem.xpath('safetyreportid/text()')[0] try: report.safetyreportid = elem.xpath('safetyreportid/text()')[0] except: pass try: report.safetyreportversion = int_validator(elem.xpath('safetyreportversion/text()')[0]) except: pass report.importedfilename = filename try: report.primarysourcecountry = str(elem.xpath('primarysourcecountry/text()')[0]) except: pass try: report.occurcountry = str(elem.xpath('occurcountry/text()')[0]) except: pass try: report.transmissiondateformat = str(elem.xpath('transmissiondateformat/text()')[0]) report.transmissiondate = datetime_validator(str(elem.xpath('transmissiondateformat/text()')[0]), str(elem.xpath('transmissiondate/text()')[0])) except: pass try: report.reporttype = int_validator(elem.xpath('reporttype/text()')[0]) except: pass try: report.serious = boolean_validator(str(elem.xpath('serious/text()')[0])) except: pass try: report.seriousnessdeath = boolean_validator(str(elem.xpath('seriousnessdeath/text()')[0])) except: pass try: report.seriousnesslifethreatening = boolean_validator(str(elem.xpath('seriousnesslifethreatening/text()')[0])) except: pass try: report.seriousnesshospitalization = boolean_validator(str(elem.xpath('seriousnesshospitalization/text()')[0])) except: pass try: report.seriousnessdisabling = boolean_validator(str(elem.xpath('seriousnessdisabling/text()')[0])) except: pass try: report.seriousnesscongenitalanomali = boolean_validator(str(elem.xpath('seriousnesscongenitalanomali/text()')[0])) except: pass try: report.seriousnessother = boolean_validator(str(elem.xpath('seriousnessother/text()')[0])) except: pass try: report.receivedateformat = str(elem.xpath('receivedateformat/text()')[0]) report.receivedate = datetime_validator(str(elem.xpath('receivedateformat/text()')[0]), str(elem.xpath('receivedate/text()')[0])) except: pass try: report.recieptdateformat = str(elem.xpath('receiptdateformat/text()')[0]) report.recieptdate = datetime_validator(str(elem.xpath('receiptdateformat/text()')[0]), str(elem.xpath('receiptdate/text()')[0])) except: pass try: report.fullfillexpeditecriteria = boolean_validator(str(elem.xpath('fulfillexpeditecriteria/text()')[0])) except: pass try: report.companynumb = str(elem.xpath('companynumb/text()')[0]) except: pass try: report.reportercountry = str(elem.xpath('primarysource/reportercountry/text()')[0]) except: pass try: report.duplicate = null_boolean_validator(str(elem.xpath('duplicate/text()')[0])) except: pass try: report.qualification = int_validator(elem.xpath('primarysource/qualification/text()')[0]) except: pass try: report.sendertype = int_validator(elem.xpath('sender/sendertype/text()')[0]) except: pass try: report.senderorganization = str(elem.xpath('sender/senderorganization/text()')[0]) except: pass try: report.receivertype = int_validator(elem.xpath('receiver/receivertype/text()')[0]) except: pass try: report.receiverorganization = str(elem.xpath('receiver/receiverorganization/text()')[0]) except: pass try: report.patientonsetage = float(elem.xpath('patient/patientonsetage/text()')[0]) except: pass try: report.patientonsetageunit = int_validator(elem.xpath('patient/patientonsetageunit/text()')[0]) except: pass try: report.patientweight = float(elem.xpath('patient/patientweight/text()')[0]) except: pass try: report.patientsex = int_validator(elem.xpath('patient/patientsex/text()')[0]) except: pass report.save() reportduplicates = elem.xpath('reportduplicate') # We delete any existing reportduplicates ReportDuplicate.objects.get(report=safetyreportid).delete() for item in reportduplicates: duplicate = ReportDuplicate() duplicate.report = Report.objects.get(safetyreportid=report.safetyreportid) try: duplicate.duplicatesource = str(item.xpath('duplicatesource/text()')[0]) except: pass try: duplicate.duplicatenumb = str(item.xpath('duplicatenumb/text()')[0]) except: pass duplicate.save() reactions = elem.xpath('patient/reaction') # We delete any existing reactions Reaction.objects.get(report=safetyreportid).delete() for item in reactions: reaction = Reaction() reaction.report = Report.objects.get(safetyreportid=report.safetyreportid) try: reaction.reactionmeddrapt = str(item.xpath('reactionmeddrapt/text()')[0]) except: pass try: reaction.reactionmeddraversionpt = str(item.xpath('reactionmeddraversionpt/text()')[0]) except: pass try: reaction.reactionoutcome = int_validator(item.xpath('reactionoutcome/text()')[0]) except: pass reaction.save() drugs = elem.xpath('patient/drug') # We delete any existing drugs Drug.objects.get(report=safetyreportid).delete() for item in drugs: drug = Drug() drug.report = Report.objects.get(safetyreportid=report.safetyreportid) try: drug.drugcharacterization = int_validator(item.xpath('drugcharacterization/text()')[0]) except: pass try: drug.medicinalproduct = str(item.xpath('medicinalproduct/text()')[0]) except: pass try: drug.drugbatchnumb = str(item.xpath('drugbatchnumb/text()')[0]) except: pass try: drug.drugauthorizationnumb = str(item.xpath('drugauthorizationnumb/text()')[0]) except: pass try: drug.drugstructuredosagenumb = str(item.xpath('drugstructuredosagenumb/text()')[0]) except: pass try: drug.drugstructureddosageunit = int_validator(item.xpath('drugstructureddosageunit/text()')[0]) except: pass try: drug.drugseparatedosagenumb = float(item.xpath('drugseparatedosagenumb/text()')[0]) except: pass try: drug.drugintervaldosageunitnumb = float(item.xpath('drugintervaldosageunitnumb/text()')[0]) except: pass try: drug.drugintervaldosagedefinition = int_validator(item.xpath('drugintervaldosagedefinition/text()')[0]) except: pass try: drug.drugcumulativedosagenumb = float(item.xpath('drugcumulativedosagenumb/text()')[0]) except: pass try: drug.drugcumulativedosageunit = int_validator(item.xpath('drugcumulativedosageunit/text()')[0]) except: pass try: drug.drugdosagetext = str(item.xpath('drugdosagetext/text()')[0]) except: pass try: drug.drugdosageform = str(item.xpath('drugdosageform/text()')[0]) except: pass try: drug.drugadministrationroute = int_validator(item.xpath('drugadministrationroute/text()')[0]) except: pass try: drug.drugindication = str(item.xpath('drugindication/text()')[0]) except: pass try: drug.drugstartdateformat = str(item.xpath('drugstartdateformat/text()')[0]) drug.drugstartdate = datetime_validator(str(item.xpath('drugstartdateformat/text()')[0]), str(item.xpath('drugstartdate/text()')[0])) except: pass try: drug.drugenddateformat = str(item.xpath('drugenddateformat/text()')[0]) drug.drugenddate = datetime_validator(str(item.xpath('drugenddateformat/text()')[0]), str(item.xpath('drugenddate/text()')[0])) except: pass try: drug.drugtreatmentduration = float(item.xpath('drugtreatmentduration/text()')[0]) except: pass try: drug.drugtreatmentdurationunit = int_validator(item.xpath('drugtreatmentdurationunit/text()')[0]) except: pass try: drug.actiondrug = int_validator(item.xpath('actiondrug/text()')[0]) except: pass try: drug.drugrecurreadministration = null_boolean_validator(str(item.xpath('drugrecurreadministration/text()')[0])) except: pass try: drug.drugadditional = null_boolean_validator(str(item.xpath('drugadditional/text()')[0])) except: pass drug.save()
def send(request): # Obtenemos los campos comunes entre reportes report_type = request.POST.get("form_type", "") doc_name = request.POST.get("nombre_dr", "") patient_name = request.POST.get("nombre_pac", "") consult_date = request.POST.get("fecha", "") observ = request.POST.get("observaciones", "") # Variables comunes url = "https://android.googleapis.com/gcm/send" headers = {"Content-Type": "application/json", "Authorization": "key=AIzaSyCH7B7qMMbLnQdj6WG1yuvPp3SlsLHtBds"} # Creamos un objeto del tipo reporte del que heredará la info el reporte específico rep = Report( doc_name=doc_name, patient_name=patient_name, consult_date=consult_date, report_type=report_type, observ=observ ) rep.save() if report_type == "psicologico": # Obtenemos campos únicos de reporte psicologico patient_state = request.POST.get("estado_pac", "") suggest = request.POST.get("sugerencias", "") psy = PsyReport(report=rep, patient_state=patient_state, suggest=suggest) psy.save() print >>sys.stderr, psy.report # Payload del reporte psicologico payload = { "data": { "id": psy.report.id, "tipo": report_type, "fecha": consult_date, "doctor": doc_name, "paciente": patient_name, "observaciones": observ, "sugerencias": suggest, }, "registration_ids": [ "APA91bHDXfzISMoo6OfqhhODnU7TeNzqCxeE7lYZHhdI801wazh1e7vbITZVTqwKU5avNW0myInlZW3Aat3S8gzqawN9G5fQEkMVNvqkDHRRYt1IDsFrPuc" ], } elif report_type == "nutricional": # Obtenemos campos únicos de reporte nutricional weight = request.POST.get("peso", "") height = request.POST.get("talla", "") pressure = request.POST.get("presion", "") risk_factors = request.POST.get("fac_riesgo", "") appetite = request.POST.get("est_apetito", "") diet = request.POST.get("dieta", "") nut = NutReport( report=rep, weight=weight, height=height, pressure=pressure, risk_factors=risk_factors, appetite=appetite, diet=diet, ) nut.save() # Payload del reporte psicologico payload = { "data": { "id": nut.report.id, "tipo": report_type, "fecha": consult_date, "doctor": doc_name, "paciente": patient_name, "observaciones": observ, "peso": weight, "talla": height, "presion": pressure, "fac_riesgo": risk_factors, "est_apetito": appetite, "dieta": diet, }, "registration_ids": [ "APA91bHDXfzISMoo6OfqhhODnU7TeNzqCxeE7lYZHhdI801wazh1e7vbITZVTqwKU5avNW0myInlZW3Aat3S8gzqawN9G5fQEkMVNvqkDHRRYt1IDsFrPuc" ], } # El envío de la notificación es común para los reportes try: # r = requests.post(url, data=json.dumps(payload)) r = requests.post(url, headers=headers, data=json.dumps(payload)) except requests.exceptions.ConnectionError: if report_type == "psicologico": return render( request, "reports/psychological.html", {"error_message": "No hay conexión a internet, intente más tarde"}, ) elif report_type == "nutricional": return render( request, "reports/nutritional.html", {"error_message": "No hay conexión a internet, intente más tarde"} ) else: print >>sys.stderr, "POST request response: ", r.status_code if r.status_code == 200: code = 0 else: code = 1 return HttpResponseRedirect(reverse("reports:results", args=(rep.id, code))) pass