def stat(id=None): # when we add observation for survey using form-post only if request.form: if Observation.request_create_form(survey_id=id, value=request.form.get('value'), frequency=request.form.get('frequency')): return "Observation Added for Survey : {}".format(id) else: return "Operation not permitted" elif request.args: return Observation.get_delete_put_post(id) else: return Observation.get_delete_put_post(id)
def new_standalone_observation(): """Create new standalone observation""" form = StandaloneObservationNewForm() _assign_equipment_choices(form) if request.method == 'POST' and form.validate_on_submit(): location_position = None location_id = None if isinstance(form.location.data, int) or form.location.data.isdigit(): location_id = int(form.location.data) else: location_position = form.location.data observation = Observation( user_id=current_user.id, date_from=form.date_from.data, date_to=form.date_to.data, location_id=location_id, location_position=location_position, sqm=form.sqm.data, faintest_star=form.faintest_star.data, seeing=form.seeing.data, telescope_id=form.telescope.data if form.telescope.data != -1 else None, eyepiece_id=form.eyepiece.data if form.eyepiece.data != -1 else None, filter_id=form.filter.data if form.filter.data != -1 else None, notes=form.notes.data, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now()) db.session.add(observation) db.session.commit() flash(gettext('Observation successfully created'), 'form-success') return redirect( url_for('main_standalone_observation.standalone_observation_edit', observation_id=observation.id)) location, location_position = _get_location_data2_from_form(form) return render_template('main/observation/standalone_observation_edit.html', form=form, is_new=True, location=location, location_position=location_position)
def process_mapping_encounter(self, json_result, user_id): print("process mapping encounter") try: mapped_girl_object = self.get_form_id_and_extract_json_object( json_result) next_of_kin_number = None voucher_number = "" attended_anc_visit = False bleeding = False fever = False swollenfeet = False blurred_vision = False voucher_number_creation = False nationality = "Ugandan" disabled = False mapping_encounter = MappingEncounter() try: odk_instance_id = mapped_girl_object["meta"][0]["instanceID"][ 0] except Exception as e: print(e) odk_instance_id = "abc123" demographic1 = mapped_girl_object["GirlDemographic"][0] first_name = demographic1["FirstName"][0] last_name = demographic1["LastName"][0] girls_phone_number = demographic1["GirlsPhoneNumber"][0] dob = demographic1["DOB"][0] try: demographic2 = mapped_girl_object["GirlDemographic2"][0] next_of_kin_number = demographic2["NextOfKinNumber"][0] except Exception as e: print(e) try: nationality_group = mapped_girl_object["NationalityGroup"][0] nationality = nationality_group['Nationality'][0] except KeyError or IndexError as e: print(e) girl_location = mapped_girl_object["GirlLocation"][0] # use filter and get first because there are so some duplicate locations parish = Parish.objects.filter(name__icontains=replace_underscore( girl_location["parish"][0])).first() village = Village.objects.filter( Q(name__icontains=replace_underscore( girl_location["village"][0])) & Q(parish=parish)).first() try: disability_group = mapped_girl_object["DisabilityGroup"][0] disabled = disability_group['Disability'][0] == "yes" except KeyError or IndexError as e: print(e) observations3 = mapped_girl_object["Observations3"][0] marital_status = observations3["marital_status"][0] education_level = replace_underscore( observations3["education_level"][0]) last_menstruation_date = observations3["MenstruationDate"][0] try: observations1 = mapped_girl_object["Observations1"][0] bleeding = observations1["bleeding"][0] == "yes" fever = observations1["fever"][0] == "yes" observations2 = mapped_girl_object["Observations2"][0] swollenfeet = observations2["swollenfeet"][0] == "yes" blurred_vision = observations2["blurred_vision"][0] == "yes" except Exception: print(traceback.print_exc()) try: voucher_card_group = mapped_girl_object["VouncherCardGroup"][0] has_voucher_card = voucher_card_group["VoucherCard"][ 0] == "yes" if has_voucher_card: voucher_number = voucher_card_group["VoucherNumber"][0] else: voucher_number_creation = voucher_card_group[ "VoucherNumberCreation"][0] == "yes" except KeyError or IndexError: print(traceback.print_exc()) user = User.objects.get(id=user_id) print(user) # incase the village does not exist use the health worker's village if not village: village = user.village # incase the girl already exists with the same name, # create a new girl and swap the new girl for the old one with updated data old_girl = Girl.objects.filter( Q(first_name__icontains=first_name) & Q(last_name__icontains=last_name)) if old_girl: if len(voucher_number) == 0: voucher_number = old_girl.first().voucher_number edited_girl = Girl( first_name=first_name, last_name=last_name, village=village, phone_number=girls_phone_number, user=user, disabled=disabled, voucher_number=voucher_number, next_of_kin_phone_number=next_of_kin_number, nationality=nationality, education_level=education_level, dob=dob, marital_status=marital_status, last_menstruation_date=last_menstruation_date, odk_instance_id=odk_instance_id) edited_girl.save() girl = edited_girl # swap the old girl for the edited girl old_girl = old_girl.first() old_appointments = old_girl.appointment_set.all() for appointment in old_appointments: appointment.girl = edited_girl appointment.save(update_fields=['girl']) old_referrals = old_girl.referral_set.all() for referral in old_referrals: referral.girl = edited_girl referral.save(update_fields=['girl']) # lastly delete the old girl old_girl.delete() else: voucher_number = voucher_number if user.district.name.lower( ) in MSI_DISTRICTS else "" new_girl = Girl.objects.create( first_name=first_name, last_name=last_name, village=village, phone_number=girls_phone_number, user=user, nationality=nationality, disabled=disabled, next_of_kin_phone_number=next_of_kin_number, education_level=education_level, dob=dob, marital_status=marital_status, last_menstruation_date=last_menstruation_date, voucher_number=voucher_number, odk_instance_id=odk_instance_id) girl = new_girl try: # incase girl who has already had ANC visit is mapped by midwife # save that date and create an anc visit anc_previous_group = mapped_girl_object[ "ANCAppointmentPreviousGroup"][0] attended_anc_visit = anc_previous_group[ "AttendedANCVisit"][0] == "yes" if attended_anc_visit: previous_appointment_date = anc_previous_group[ "ANCDatePrevious"][0] self.auto_generate_appointment( new_girl, user, previous_appointment_date) else: self.auto_generate_appointment(new_girl, user) except Exception: print(traceback.print_exc()) try: anc_group = mapped_girl_object["ANCAppointmentGroup"][0] next_appointment_date = anc_group["ANCDate"][0] appointment = Appointment(girl=new_girl, user=user, date=next_appointment_date) appointment.save() except Exception: print(traceback.print_exc()) observation = Observation(blurred_vision=blurred_vision, bleeding_heavily=bleeding, fever=fever, swollen_feet=swollenfeet) observation.save() mapping_encounter.observation = observation mapping_encounter.attended_anc_visit = attended_anc_visit mapping_encounter.voucher_card = voucher_number if user.district.name.lower( ) != "bundibugyo" else "" mapping_encounter.odk_instance_id = odk_instance_id mapping_encounter.user = user mapping_encounter.girl = girl mapping_encounter.save() self.save_family_planning_methods_in_mapping_encounter( mapped_girl_object, mapping_encounter) # MSI voucher are only provided to MSI districts if user.district.name.lower( ) in MSI_DISTRICTS and user.role == USER_TYPE_CHEW: self.get_and_save_msi_voucher_to_girl(girl) return Response({'result': 'success'}, status.HTTP_200_OK) except Exception: print(traceback.print_exc()) return Response({'result': 'failure'}, status.HTTP_400_BAD_REQUEST)
def process_appointment_encounter(self, girl_id, json_result, user_id): try: try: appointment_object = json_result[APPOINTMENT_FORM_MIDWIFE_NAME] except Exception: print(traceback.print_exc()) try: appointment_object = json_result[DEFAULT_TAG] except KeyError: print(traceback.print_exc()) needed_ambulance = False used_ambulance = False missed_anc_reason = "" appointment_method = "" fever = False swollenfeet = False bleeding = False blurred_vision = False try: ambulance_group = appointment_object["ambulance_group"][0] needed_ambulance = ambulance_group["needed_ambulance"][ 0] == "yes" used_ambulance = ambulance_group["used_ambulance"][0] == "yes" except Exception: print(traceback.print_exc()) try: appointment_soon_group = appointment_object[ "appointment_soon_group"][0] appointment_method = replace_underscore( appointment_soon_group["appointment_method"][0]) except Exception: print(traceback.print_exc()) missed_anc_before_group = appointment_object[ "missed_anc_before_group"][0] missed_anc_before = missed_anc_before_group["missed_anc_before"][ 0] == "yes" if missed_anc_before: missed_anc_before_group2 = appointment_object[ "missed_anc_before_group2"][0] missed_anc_reason = missed_anc_before_group2[ "missed_anc_reason"][0] if missed_anc_reason == "Other": missed_anc_reason = missed_anc_before_group2[ "missed_anc_reason_other"][0] action_taken_group = appointment_object["action_taken_group"][0] action_taken = replace_underscore( action_taken_group["action_taken_meeting_girl"][0]) if action_taken == 'other': action_taken = replace_underscore( action_taken_group["action_taken_other"][0]) schedule_appointment_group = appointment_object[ "schedule_appointment_group"][0] next_appointment_date = schedule_appointment_group[ "schedule_appointment"][0] girl = Girl.objects.get(id=girl_id) user = User.objects.get(id=user_id) try: if user.district.name.lower( ) in MSI_DISTRICTS and user.role == USER_TYPE_MIDWIFE: msi_service = appointment_object["voucher_redeem_group"][ 0]["voucher_services"][0] MSIService.objects.create(girl=girl, option=msi_service) except Exception as e: print(e) observation = Observation(blurred_vision=blurred_vision, bleeding_heavily=bleeding, fever=fever, swollen_feet=swollenfeet) observation.save() appointment = Appointment(girl=girl, user=user, date=next_appointment_date) appointment.save() appointment_encounter = AppointmentEncounter( used_ambulance=used_ambulance, needed_ambulance=needed_ambulance, missed_anc_reason=missed_anc_reason, action_taken=action_taken, appointment_method=appointment_method, missed_anc_before=missed_anc_before, appointment=appointment) appointment_encounter.observation = observation appointment_encounter.save() return Response({'result': 'success'}, 200) except Exception: print(traceback.print_exc()) return Response({'result': 'failure'}, 400)
def process_follow_up_and_delivery_encounter(self, girl_id, json_result, user_id): try: try: follow_up_object = json_result[FOLLOW_UP_FORM_CHEW_NAME] except Exception: print(traceback.print_exc()) try: follow_up_object = json_result[FOLLOW_UP_FORM_MIDWIFE_NAME] except Exception: print(traceback.print_exc()) try: follow_up_object = json_result[DEFAULT_TAG] except KeyError: print(traceback.print_exc()) print(follow_up_object) fever = False swollenfeet = False bleeding = False blurred_vision = False missed_anc_before = False missed_anc_reason = "" action_taken_by_health_person = "appointment" try: # captured in chew follow up observations1 = follow_up_object["observations1"][0] bleeding = observations1["bleeding"][0] == "yes" fever = observations1["fever"][0] == "yes" observations2 = follow_up_object["observations2"][0] swollenfeet = observations2["swollenfeet"][0] == "yes" blurred_vision = observations2["blurred_vision"][0] == "yes" except Exception: print(traceback.print_exc()) try: missed_anc_before_group = follow_up_object[ "missed_anc_before_group"][0] missed_anc_before = missed_anc_before_group[ "missed_anc_before"][0] == "yes" if missed_anc_before: missed_anc_before_group2 = follow_up_object[ "missed_anc_before_group2"][0] missed_anc_reason = replace_underscore( missed_anc_before_group2["missed_anc_reason"][0]) if missed_anc_reason == "Other": missed_anc_reason = replace_underscore( missed_anc_before_group2["missed_anc_reason_other"] [0]) except Exception: print(traceback.print_exc()) try: action_taken_group = follow_up_object[ "action_taken_by_health_person_group"][0] action_taken_by_health_person = action_taken_group[ "action_taken_by_health_person"][0] except Exception: print(traceback.print_exc()) girl = Girl.objects.get(id=girl_id) user = User.objects.get(id=user_id) if action_taken_by_health_person == "appointment": next_appointment = follow_up_object[ "schedule_appointment_group"][0]["schedule_appointment"][0] appointment = Appointment(girl=girl, user=user, date=next_appointment) appointment.save() elif action_taken_by_health_person == "delivery": self.save_delivery(follow_up_object, girl, user) elif action_taken_by_health_person in ["referral", "referred"]: Referral.objects.create(girl=girl, user=user, reason="critical") observation = Observation(blurred_vision=blurred_vision, bleeding_heavily=bleeding, fever=fever, swollen_feet=swollenfeet) observation.save() follow_up = FollowUp( girl=girl, user=user, follow_up_action_taken=action_taken_by_health_person, missed_anc_reason=missed_anc_reason, missed_anc_before=missed_anc_before, observation=observation) follow_up.save() return Response({'result': 'success'}, 200) except Exception: print(traceback.print_exc()) return Response({'result': 'failure'}, 400)
def deepskyobject_observation_log(dso_id): dso, orig_dso = _find_dso(dso_id) if dso is None: abort(404) back = request.args.get('back') if back != 'running_plan': abort(404) back_id = request.args.get('back_id') observation_plan_run = ObsSessionPlanRun.query.filter_by( id=back_id).first() if observation_plan_run is None or observation_plan_run.session_plan.user_id != current_user.id: abort(404) form = DeepskyObjectObservationLog() observation = None for o in observation_plan_run.observing_session.observations: for oi_dso in o.deepsky_objects: if oi_dso.id == dso.id: observation = o break if observation is not None: break is_new_observation_log = observation is None if is_new_observation_log: now = datetime.now() observation = Observation( observing_session_id=observation_plan_run.observing_session.id, date_from=now, date_to=now, notes=form.notes.data if form.notes.data else '', create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now(), ) observation.deepsky_objects.append(dso) if request.method == 'POST': if form.validate_on_submit(): observation.notes = form.notes.data observation.update_by = current_user.id, observation.update_date = datetime.now(), db.session.add(observation) db.session.commit() flash('Observation log successfully updated', 'form-success') return redirect( url_for('main_deepskyobject.deepskyobject_observation_log', dso_id=dso_id, back=back, back_id=back_id)) else: form.notes.data = observation.notes embed = request.args.get('embed') if embed: session['dso_embed_seltab'] = 'obs_log' prev_dso, prev_dso_title, next_dso, next_dso_title = _get_prev_next_dso( orig_dso) return render_template('main/catalogue/deepskyobject_info.html', type='observation_log', dso=dso, form=form, prev_dso=prev_dso, next_dso=next_dso, prev_dso_title=prev_dso_title, next_dso_title=next_dso_title, embed=embed, is_new_observation_log=is_new_observation_log, back=back, back_id=back_id, has_observations=False)
def test_new_observation(): observation = Observation(survey_id=1, value=3.3, frequency=10) assert observation.value == 3.3 assert observation.survey_id == 1 assert observation.frequency == 10
def test_obs_verify(): obs = repr(Observation(survey_id=1, value=1.1, frequency=10)) assert obs == '<Observation 1 1.1 10>'
def import_observations(user, import_user, import_history_rec_id, file): log_warn = [] log_error = [] oal_observations = parse(file, silence=True) # Locations oal_sites = oal_observations.get_sites() found_locations = {} add_hoc_locations = {} if oal_sites and oal_sites.get_site(): for oal_site in oal_sites.get_site(): location = None if oal_site.get_name(): location = Location.query.filter_by(name=oal_site.get_name()).first() if location is None: add_hoc_locations[oal_site.name] = (oal_site.get_latitude(), oal_site.get_longitude()) log_warn.append(lazy_gettext('OAL Location "{}" not found').format(oal_site.get_name())) else: found_locations[oal_site.get_id()] = location # Scopes found_telescopes = {} oal_scopes = oal_observations.get_scopes() if oal_scopes: for oal_scope in oal_scopes.get_scope(): model = oal_scope.get_model() telescope_type = _get_telescope_type_from_oal_scope_type(oal_scope.get_type()) vendor = oal_scope.get_vendor() aperture_mm = oal_scope.get_aperture() focal_length_mm = None fixed_magnification = None if isinstance(oal_scope, OalscopeType): focal_length_mm = oal_scope.get_focalLength() if isinstance(oal_scope, OalfixedMagnificationOpticsType): fixed_magnification = oal_scope.get_magnification() telescope_query = Telescope.query.filter_by(user_id=current_user.id) if model: telescope_query = telescope_query.filter_by(model=model) if telescope_type: telescope_query = telescope_query.filter_by(telescope_type=telescope_type) if vendor: telescope_query = telescope_query.filter_by(vendor=vendor) if aperture_mm: telescope_query = telescope_query.filter_by(aperture_mm=aperture_mm) if focal_length_mm: telescope_query = telescope_query.filter_by(focal_length_mm=focal_length_mm) if fixed_magnification: telescope_query = telescope_query.filter_by(fixed_magnification=fixed_magnification) telescope = telescope_query.first() if not telescope: telescope = Telescope( name=oal_scope.get_id(), vendor=vendor, model=model, descr='', aperture_mm=aperture_mm, focal_length_mm=focal_length_mm, fixed_magnification=fixed_magnification, telescope_type=telescope_type, is_default=False, is_active=True, is_deleted=False, import_history_rec_id=import_history_rec_id, user_id=current_user.id, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now() ) db.session.add(telescope) found_telescopes[oal_scope.get_id()] = telescope # Eyepieces found_eyepieces = {} oal_eyepieces = oal_observations.get_eyepieces() if oal_eyepieces: for oal_eyepiece in oal_eyepieces.get_eyepiece(): model = oal_eyepiece.get_model() vendor = oal_eyepiece.get_vendor() focal_length_mm = oal_eyepiece.get_focalLength() fov_deg = _get_angle_from_oal_angle(oal_eyepiece.get_apparentFOV()) eyepiece_query = Eyepiece.query.filter_by(user_id=current_user.id) if model: eyepiece_query = eyepiece_query.filter_by(model=model) if vendor: eyepiece_query = eyepiece_query.filter_by(vendor=vendor) if focal_length_mm: eyepiece_query = eyepiece_query.filter_by(focal_length_mm=focal_length_mm) if fov_deg: eyepiece_query = eyepiece_query.filter_by(fov_deg=fov_deg) eyepiece = eyepiece_query.first() if not eyepiece: eyepiece = Eyepiece( name=oal_eyepiece.get_id(), vendor=vendor, model=model, descr='', focal_length_mm=focal_length_mm, fov_deg=fov_deg, diameter_inch=None, is_active=True, is_deleted=False, import_history_rec_id=import_history_rec_id, user_id=current_user.id, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now() ) db.session.add(eyepiece) found_eyepieces[oal_eyepiece.get_id()] = eyepiece # Filters found_filters = {} oal_filters = oal_observations.get_filters() if oal_filters: for oal_filter in oal_filters.get_filter(): model = oal_filter.get_model() vendor = oal_filter.get_vendor() filter_type = _get_filter_type_from_oal_filter_kind(oal_filter.get_type()) filter_query = Filter.query.filter_by(user_id=current_user.id) if model: filter_query = filter_query.filter_by(model=model) if vendor: filter_query = filter_query.filter_by(vendor=vendor) if filter_type: filter_query = filter_query.filter_by(filter_type=filter_type) filter = filter_query.first() if not filter: filter = Filter( name=oal_filter.get_id(), vendor=vendor, model=model, descr='', filter_type=filter_type, diameter_inch=None, is_active=True, is_deleted=False, import_history_rec_id=import_history_rec_id, user_id=current_user.id, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now() ) db.session.add(filter) found_filters[oal_filter.get_id()] = filter # Lenses found_lenses = {} oal_lenses = oal_observations.get_lenses() if oal_lenses: for oal_lens in oal_lenses.get_lens(): model = oal_lens.get_model() vendor = oal_lens.get_vendor() factor = oal_lens.get_factor() lens_query = Lens.query.filter_by(user_id=current_user.id) if model: lens_query = lens_query.filter_by(model=model) if vendor: lens_query = lens_query.filter_by(vendor=vendor) if factor: lens_query = lens_query.filter_by(magnification=factor) lens = lens_query.first() if not lens: lens = Lens( name=oal_lens.get_id(), vendor=vendor, model=model, descr='', lens_type=None, magnification=factor, diameter_inch=None, is_active=True, is_deleted=False, import_history_rec_id=import_history_rec_id, user_id=current_user.id, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now() ) db.session.add(lens) found_lenses[oal_lens.get_id()] = lens # Observations oal_sessions = oal_observations.get_sessions() found_observing_sessions = {} new_observing_sessions = {} if oal_sessions and oal_sessions.get_session(): for oal_session in oal_sessions.get_session(): begin = oal_session.get_begin() end = oal_session.get_end() if begin and not end: end = begin if end and not begin: begin = end observing_session = ObservingSession.query.filter(ObservingSession.user_id == user.id) \ .filter(and_(ObservingSession.date_to >= begin, ObservingSession.date_from <= end)) \ .first() if observing_session and observing_session.update_date != observing_session.create_date: found_observing_sessions[oal_session.get_id()] = observing_session else: location = found_locations.get(oal_session.get_site()) location_position = add_hoc_locations.get(oal_session.get_site()) if location: title = location.name + ' ' + begin.strftime('%d.%m.%Y') elif begin: title = begin.strftime('%d.%m.%Y') else: title = oal_session.get_id() now = datetime.now() if not observing_session: observing_session = ObservingSession( user_id=user.id, title=title, date_from=begin, date_to=end, location_id=location.id if location else None, location_position=location_position, sqm=None, faintest_star=None, seeing=None, transparency=None, rating=None, weather=oal_session.get_weather(), equipment=oal_session.get_equipment(), notes=oal_session.get_comments(), import_history_rec_id=import_history_rec_id, create_by=import_user.id, update_by=import_user.id, create_date=now, update_date=now ) new_observing_sessions[oal_session.get_id()] = observing_session else: observing_session.title = title observing_session.date_from = begin observing_session.date_to = end observing_session.location_id = location.id if location else None observing_session.location_position = location_position observing_session.weather = oal_session.get_weather() observing_session.equipment = oal_session.get_equipment() observing_session.notes = oal_session.get_comments() observing_session.import_history_rec_id = import_history_rec_id observing_session.update_by = import_user.id observing_session.create_date = now observing_session.update_date = now found_observing_sessions[oal_session.get_id()] = observing_session db.session.add(observing_session) # Targets oal_targets = oal_observations.get_targets() found_dsos = {} found_double_stars = {} not_found_targets = set() if oal_targets and oal_targets.get_target(): for target in oal_targets.get_target(): if isinstance(target, (OaldeepSkyDS, OaldeepSkyMS)): double_star = search_double_star(target.get_name()) if double_star: found_double_stars[target.get_id()] = double_star else: not_found_targets.add(target.get_id()) log_error.append(lazy_gettext('Double star "{}" not found').format(target.get_name())) else: normalized_name = normalize_dso_name_ext(denormalize_dso_name(target.get_name())) dso = DeepskyObject.query.filter_by(name=normalized_name).first() if dso: found_dsos[target.get_id()] = dso else: not_found_targets.add(target.get_id()) log_error.append(lazy_gettext('DSO "{}" not found').format(target.get_name())) oal_observations = oal_observations.get_observation() for oal_observation in oal_observations: observing_session = found_observing_sessions.get(oal_observation.get_session()) is_session_new = False if not observing_session: observing_session = new_observing_sessions.get(oal_observation.get_session()) is_session_new = True observed_double_star = found_double_stars.get(oal_observation.get_target()) observed_dso = found_dsos.get(oal_observation.get_target()) if not observed_dso and not observed_double_star: if oal_observation.get_target() not in not_found_targets: log_error.append(lazy_gettext('OAL Target "{}" not found.').format(oal_observation.get_target())) continue observation = None if not is_session_new: for obs in observing_session.observations: if obs.target_type == ObservationTargetType.DBL_STAR: if observed_double_star and observed_double_star.id == obs.double_star_id: observation = obs elif obs.target_type == ObservationTargetType.DSO: if observed_dso: for dso in obs.deepsky_objects: if dso.id == observed_dso.id: observation = obs break if observation: break if observation and observation.create_date != observation.update_date: log_warn.append(lazy_gettext('OAL Observation "{}" for session "{}" already exists and was modified by user.').format(oal_observation.get_id(), oal_observation.get_session())) else: notes = '' if oal_observation.get_result(): notes = oal_observation.get_result()[0].get_description() location = found_locations.get(oal_observation.get_site()) location_position = add_hoc_locations.get(oal_observation.get_site()) if observing_session: if location and observing_session.location_id == location.id: location = None if location_position and observing_session.location_position == location_position: location_position = None telescope = found_telescopes.get(oal_observation.get_scope()) if oal_observation.get_scope() else None eyepiece = found_eyepieces.get(oal_observation.get_eyepiece()) if oal_observation.get_eyepiece() else None filter = found_filters.get(oal_observation.get_filter()) if oal_observation.get_filter() else None oal_lens = oal_observation.get_lens() lens = found_lenses.get(oal_observation.get_lens()) if oal_observation.get_lens() else None now = datetime.now() if not observation: observation = Observation( user_id=current_user.id, observing_session_id=observing_session.id if observing_session else None, location_id=location.id if location else None, location_position=location_position, date_from=oal_observation.get_begin(), date_to=oal_observation.get_end(), sqm=_get_sqm_from_oal_surface_brightness(oal_observation.get_sky_quality()), faintest_star=oal_observation.get_faintestStar(), seeing=_get_seeing_from_oal_seeing(oal_observation.get_seeing()), telescope_id=telescope.id if telescope else None, eyepiece_id=eyepiece.id if eyepiece else None, filter_id=filter.id if filter else None, lens_id=lens.id if lens else None, notes=notes, import_history_rec_id=import_history_rec_id, create_by=current_user.id, update_by=current_user.id, create_date=now, update_date=now, ) if observed_double_star: observation.double_star_id = observed_double_star.id observation.target_type = ObservationTargetType.DBL_STAR db.session.add(observation) if observed_dso: observation.deepsky_objects.append(observed_dso) observation.target_type = ObservationTargetType.DSO if observing_session: observing_session.observations.append(observation) else: observation.observing_session_id = observing_session.id if observing_session else None observation.location_id = location.id if location else None observation.location_position = location_position observation.date_from = oal_observation.get_begin() observation.date_to = oal_observation.get_end() observation.sqm = _get_sqm_from_oal_surface_brightness(oal_observation.get_sky_quality()) observation.faintest_star = oal_observation.get_faintestStar() observation.seeing = _get_seeing_from_oal_seeing(oal_observation.get_seeing()) observation.telescope_id = telescope.id if telescope else None observation.eyepiece_id = eyepiece.id if eyepiece else None observation.filter_id = filter.id if filter else None observation.lens_id = lens.id if lens else None observation.notes = notes observation.import_history_rec_id = import_history_rec_id observation.update_by = current_user.id observation.create_date = now # set create date to update date to easy detect user modifications observation.update_date = now db.session.add(observation) if is_session_new and observing_session: if not observing_session.sqm and oal_observation.get_sky_quality(): observing_session.sqm = _get_sqm_from_oal_surface_brightness(oal_observation.get_sky_quality()) if not observing_session.faintest_star and oal_observation.get_faintestStar(): observing_session.faintest_star = oal_observation.get_faintestStar() if not observing_session.seeing and oal_observation.get_seeing(): observing_session.seeing = _get_seeing_from_oal_seeing(oal_observation.get_seeing()) db.session.commit() return log_warn, log_error
def observing_session_items_edit(observing_session_id): """Update observing_session items""" observing_session = ObservingSession.query.filter_by( id=observing_session_id).first() _check_observing_session(observing_session) form = ObservingSessionItemsEditForm() if request.method == 'POST': if form.validate_on_submit(): for observation in observing_session.observations: observation.deepsky_objects = [] db.session.delete(observation) observing_session.observations.clear() for item_form in form.items[1:]: item_time = datetime.combine(observing_session.date_from, item_form.date_from.data) if ':' in item_form.comp_notes.data: targets, notes = item_form.comp_notes.data.split(':', 1) else: targets, notes = item_form.comp_notes.data.strip(), '' observation = Observation( observing_session_id=observing_session.id, user_id=current_user.id, date_from=item_time, date_to=item_time, notes=notes, create_by=current_user.id, update_by=current_user.id, create_date=datetime.now(), update_date=datetime.now(), ) observing_session.observations.append(observation) observation.deepsky_objects = [] dsos, double_star, not_found = parse_observation_targets( targets) if double_star: observation.double_star_id = double_star.id observation.target_type = ObservationTargetType.DBL_STAR elif dsos: for dso in dsos: observation.deepsky_objects.append(dso) observation.target_type = ObservationTargetType.DSO db.session.add(observing_session) db.session.commit() if form.goback.data == 'true': return redirect( url_for('main_observing_session.observing_session_info', observing_session_id=observing_session.id)) return redirect( url_for('main_observing_session.observing_session_items_edit', observing_session_id=observing_session.id)) else: for oi in observing_session.observations: oif = form.items.append_entry() if oi.double_star: targets_comp = oi.double_star.get_common_norm_name() else: targets_comp = ','.join( [dso.name for dso in oi.deepsky_objects]) targets_comp += ':' oif.comp_notes.data = targets_comp + oi.notes oif.date_from.data = oi.date_from return render_template( 'main/observation/observing_session_items_edit.html', form=form, observing_session=observing_session)