Example #1
0
def find_gesture():
    gest_code = request.args.get('gesture', None)
    healthcare_plan_id = request.args.get('healthcare_plan_id', None)
    patient_id = int(request.args.get('patient_id', None))
    patient, appointment = checks.get_patient_appointment(
                                                        patient_id=patient_id)
    if gest_code:
        gest_code = gest_code.split(" ")
        words = u"%"
        for word in gest_code:
            words = words + u'{}%'.format(word)
        cotations = (
            meta.session.query(act.Cotation)
                .join(act.Gesture)
                .filter(act.Cotation.healthcare_plan_id == healthcare_plan_id)
                .filter(or_(
                    act.Gesture.alias.ilike(words),
                    act.Gesture.code.ilike(words),
                    act.Gesture.name.ilike(words)
                    )
                )
                .all()
        )
        
        if not cotations:
            return jsonify(success=False)

        gestures = {}
        for cotation in cotations:
            gestures[str(cotation.id)] = (cotation.gesture.name,
                                            cotation.gesture.code,
                                            str(cotation.price))
        return jsonify(success=True, **gestures)

    return jsonify(success=False)
Example #2
0
def add_to_materio_vigilance(appointment_id, quantity, material):
    """ 
        update both:
            materio_vigilance.quantity_used and material.actual_quantity
    """
    patient, appointment = checks.get_patient_appointment(
                                                appointment_id=appointment_id)
    materio_vigilance = ( 
        meta.session.query(traceability.MaterioVigilance)
            .filter(
                traceability.MaterioVigilance.appointment_id == appointment_id,
                traceability.MaterioVigilance.material_id == material.id )
            .one_or_none()
    )
    if not materio_vigilance:
        values = {
            'material_id': material.id,
            'appointment_id': appointment_id,
            'quantity_used': quantity
        }
        new_materio_vigilance = traceability.MaterioVigilance(**values)
        meta.session.add(new_materio_vigilance)
        meta.session.commit()
        materio_vigilance = new_materio_vigilance
    else:
        materio_vigilance.quantity_used = (
            materio_vigilance.quantity_used + quantity )
        meta.session.commit()

    material.actual_quantity = ( material.actual_quantity - quantity )
    meta.session.commit()
    return materio_vigilance
Example #3
0
def list_statement(patient_id, appointment_id):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY ]
    if session['role'] not in authorized_roles:
        return abort(403)

    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    quotes = ( meta.session.query(statements.Quote)
            .filter(statements.Quote.patient_id == patient_id)
            .join(schedule.Appointment, schedule.Agenda)
            .order_by(schedule.Agenda.starttime.desc())
            .all()
    )
    bills = ( meta.session.query(statements.Bill)
            .filter(statements.Bill.patient_id == patient_id)
            .join(schedule.Appointment, schedule.Agenda)
            .order_by(schedule.Agenda.starttime.desc())
            .all()
    )
    if constants.LOCALE == 'br':
        nfes = (meta.session.query(statements.NotaFiscalBr)
            .filter(statements.NotaFiscalBr.patient_id == patient_id)
            .order_by(statements.NotaFiscalBr.timestamp.desc())
            .all()
        )
    else:
        nfes = []
    return render_template('list_statements.html', patient=patient,
                                        appointment=appointment,
                                        quotes_id='',
                                        quotes=quotes,
                                        bills=bills,
                                        nfes=nfes,
                                        constants=constants)
Example #4
0
def list_acts(patient_id, appointment_id=0):
    """
    Sends to template a list of tuples :
    ( gesture, tooth, act_info, act_specialty )
    """
    # Everybody but admin should enter this function ; however,
    # what is displayed should depends on whom is looking.
    # This will be taken care of in the html_template, by jinja.
    if session['role'] == constants.ROLE_ADMIN:
        return redirect(url_for('index'))

    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    acts = checks.get_patient_acts(patient.id, None,
            [ act.AppointmentCotationReference.appointment_id, ]
            )
    payments = ( meta.session.query(compta.Payment)
        .filter(compta.Payment.patient_id == patient_id)
        .all()
    )
    return render_template("list_patient_acts.html",
                            patient=patient,
                            appointment=appointment,
                            acts=acts,
                            payments=payments)
Example #5
0
    def add_nota_fiscal(patient_id, appointment_id=0):
        authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY ]
        if session['role'] not in authorized_roles:
            return abort(403)
        patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
        
        document_form = NotaFiscalForm(request.form)
        if request.method == 'POST' and document_form.validate():
            document_data = request.files[document_form.document.name].read()
            if document_data:
                new_file = insert_document_in_db(document_data,
                                document_form.document_type.data, appointment)
                
                values = {
                    'patient_id': patient_id,
                    'document_id': new_file.id,
                }
                new_nota_fiscal = statements.NotaFiscalBr(**values)
                meta.session.add(new_nota_fiscal)
                meta.session.commit()

        return render_template('add_nota_fiscal.html', patient=patient,
                                            appointment=appointment,
                                            document_form=document_form)
Example #6
0
def add_file_to_tooth_event(patient_id, appointment_id, event_id):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT ]
    if session['role'] not in authorized_roles:
        return abort(403)

    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    event = ( meta.session.query(teeth.Event)
                .filter(teeth.Event.id == event_id)
                .one()
    )
    document_form = DocumentForm(request.form)
    if document_form.validate():
        document_data = request.files[document_form.document.name].read()
        if document_data:
            new_file = insert_document_in_db(document_data, 
                                document_form.document_type.data, appointment)
            if new_file not in event.files:
                event.files.append(new_file)
                meta.session.commit()

    return redirect(url_for('show_tooth', patient_id=patient_id,
                                        appointment_id=appointment_id,
                                        tooth_codename=event.tooth.codename))
Example #7
0
def add_patient_survey(appointment_id):
    patient, appointment = checks.get_patient_appointment(appointment_id=appointment_id)
    patient_survey_form = PatientSurveyForm(request.form)

    patient_survey_form.appointment_id.choices = [
        (appointment.id, appointment.agenda.starttime)
        for appointment in meta.session.query(schedule.Appointment)
        .filter(schedule.Appointment.patient_id == patient.id)
        .all()
    ]

    if patient_survey_form.validate():
        # !!! Beware of this two variables really seemful ! Bad.
        anamnesis_appointment = (
            meta.session.query(schedule.Appointment)
            .filter(schedule.Appointment.id == patient_survey_form.appointment_id.data)
            .one()
        )
        appointment_anamnesis = (
            meta.session.query(anamnesis.Anamnesis)
            .filter(anamnesis.Anamnesis.appointment_id == anamnesis_appointment.id)
            .all()
        )

        document_data = request.files[patient_survey_form.document.name].read()
        if document_data:
            new_file = insert_document_in_db(document_data, constants.FILE_ANAMNESIS, anamnesis_appointment)
            for anamnesis_entry in appointment_anamnesis:
                if not anamnesis_entry.file_id:
                    anamnesis_entry.file_id = new_file.id
                    meta.session.commit()

    return redirect(url_for("list_anamnesis", patient_id=patient.id, appointment_id=appointment.id))
Example #8
0
def choose_clinic_gestures_from_cotation(appointment_id):
    """
        The POST action comes from view_clinic_report.
    """
    patient, appointment = checks.get_patient_appointment(
                                                appointment_id=appointment_id)
    form = ChooseCotationForReportForm(request.form)
    form.cotation_id.choices = [ (cot.id, cot.gesture.name) for cot in
        meta.session.query(act.Cotation)
            .join(act.Gesture, act.Specialty)
            .order_by(act.Specialty.name, act.Gesture.name)
            .all()
    ]
    if form.validate():
        # define which cotation we are working with
        cotation = ( meta.session.query(act.Cotation)
            .filter(act.Cotation.id == form.cotation_id.data)
            .one()
        )
        # Define anatomic_locations we are working with
        anatomic_locations = ""
        if not form.anatomic_location.data:
            form.anatomic_location.data = 0
        try:
            if int(form.anatomic_location.data) >= 0 :
                anatomic_locations = str(form.anatomic_location.data)
        except ValueError:
            for idx, anat_loc in\
                enumerate(teeth.get_teeth_list(form.anatomic_location.data)) :
                if idx:
                    anatomic_locations = anatomic_locations + ","
                anatomic_locations = anatomic_locations + str(anat_loc)

        # create form with clinic_gestures associated with this cotation
        cg_form = ClinicGesturesFromCotationForm(request.form)
        for cg_cot_ref in sorted(cotation.clinic_gestures,
                                key=lambda cg_cot_ref: (
                                    cg_cot_ref.appointment_number,
                                    cg_cot_ref.sequence )
                                                                         ):
            cg_keep_form = ClinicGestureKeepForm(request.form)
            cg_keep_form.clinic_gesture_id = cg_cot_ref.clinic_gesture_id
            cg_keep_form.clinic_gesture_data = cg_cot_ref.clinic_gesture.name
            cg_keep_form.keep = cg_cot_ref.appears_on_clinic_report
            cg_form.clinic_gestures.append_entry(cg_keep_form)
        
#        cg_form.clinic_gestures.entries = [ entry for entry in 
#            cg_form.clinic_gestures.entries if entry.data['clinic_gesture_id'] 
#        ]
        cg_form.price.data = cotation.price
        return render_template('choose_clinic_gestures_from_cotation.html', 
                                    anatomic_locations=anatomic_locations,
                                                    patient=patient,
                                                    appointment=appointment,
                                                    cotation_id=cotation.id,
                                                                form=cg_form,
                                                    constants=constants)
    return redirect(url_for('view_clinic_report', 
                                                appointment_id=appointment.id))
Example #9
0
def update_appointment(body_id, appointment_id):
    if session['role'] == constants.ROLE_ADMIN:
        return redirect(url_for('index'))

    patient, appointment = checks.get_patient_appointment(body_id, 
                                                                appointment_id)
    agenda_form = AgendaForm(request.form)
    appointment_form = AppointmentForm(request.form)
    appointment_form.dentist_id.choices = [ (user.id, user.firstname + " " 
                                           + user.lastname ) for user in
                            meta.session.query(users.OdontuxUser).filter(
                            users.OdontuxUser.role == constants.ROLE_DENTIST)\
                            .all()
    ]
    appointment_form.dental_unit_id.choices = [ 
                        (dental_unit.id, dental_unit.name) for dental_unit in
                            meta.session.query(users.DentalUnit).all() 
    ]

    if (request.method == 'POST' and agenda_form.validate()
        and appointment_form.validate() ):
        # get the agenda entry:
        agenda = ( meta.session.query(schedule.Agenda)
            .filter(schedule.Agenda.appointment_id == appointment_id)
            .one()
        )
        # verify the day_time infos
        (starttime, endtime) = agenda_handler(agenda_form.day.data,
                       agenda_form.starthour.data, agenda_form.startmin.data, 
                       agenda_form.durationhour.data, 
                       agenda_form.durationmin.data,
                       agenda_form.endhour.data, agenda_form.endmin.data)
        # update appointment infos:
        for f in get_appointment_field_list():
            setattr(appointment, f,  getattr(appointment_form, f).data)
        for f,g in (("starttime", starttime), ("endtime", endtime)):
            setattr(agenda, f, g)
        meta.session.commit()
        return redirect(url_for('patient_appointment', 
                                                appointment_id=appointment_id))
    
    (day, starthour, startmin, durationhour, durationmin, endhour, endmin) = \
            reverse_agenda_handler(appointment.agenda.starttime, 
                                   appointment.agenda.endtime)

    # prepopulate agenda fields :
    for f,g in ( ("day", day), ("starthour", starthour), 
                 ("startmin", startmin), ("durationhour", durationhour),
                 ("durationmin", durationmin), ("endhour", endhour),
                 ("endmin", endmin) ):
        getattr(agenda_form, f).data = g
    # prepoputate appointments fields:
    for f in get_appointment_field_list():
        getattr(appointment_form, f).data = getattr(appointment, f)
    return render_template('update_appointment.html', 
                            patient=patient,
                            appointment_form=appointment_form,
                            agenda_form=agenda_form,
                            appointment=appointment)
Example #10
0
def list_anamnesis(patient_id, appointment_id=None):
    authorized_roles = [constants.ROLE_DENTIST, constants.ROLE_NURSE, constants.ROLE_ASSISTANT]
    if session["role"] not in authorized_roles:
        return redirect(url_for("index"))

    survey_form = ChooseSurveyForm(request.form)
    survey_form.survey_id.choices = meta.session.query(anamnesis.Survey.id, anamnesis.Survey.name).all()

    patient, appointment = checks.get_patient_appointment(patient_id, appointment_id)
    global_anamnesis = with_polymorphic(anamnesis.Anamnesis, "*")
    patient_anamnesis = (
        meta.session.query(global_anamnesis)
        .filter(anamnesis.Anamnesis.patient_id == patient_id)
        .order_by(
            anamnesis.Anamnesis.alert.desc(),
            anamnesis.Anamnesis.anamnesis_type,
            anamnesis.MedicalHistory.type,
            anamnesis.MedicalHistory.disease,
            anamnesis.Anamnesis.time_stamp,
        )
        .all()
    )

    doctor = meta.session.query(md.MedecineDoctor).filter(md.MedecineDoctor.id == patient.gen_doc_id).one_or_none()

    patient_survey_form = PatientSurveyForm(request.form)
    patient_survey_form.appointment_id.choices = [
        (appointment.id, appointment.agenda.starttime)
        for appointment in meta.session.query(schedule.Appointment)
        .filter(
            schedule.Appointment.patient_id == patient.id,
            schedule.Appointment.id.in_([anamnesis_entry.appointment_id for anamnesis_entry in patient_anamnesis]),
        )
        .join(schedule.Agenda)
        .order_by(schedule.Agenda.starttime.desc())
        .all()
    ]

    anamnesis_files = (
        meta.session.query(documents.Files)
        .filter(documents.Files.id.in_([anamn.file_id for anamn in patient_anamnesis]))
        .order_by(documents.Files.timestamp.desc())
        .all()
    )

    return render_template(
        "patient_anamnesis.html",
        patient=patient,
        appointment=appointment,
        patient_anamnesis=patient_anamnesis,
        doctor=doctor,
        survey_form=survey_form,
        constants=constants,
        patient_survey_form=patient_survey_form,
        anamnesis_files=anamnesis_files,
    )
Example #11
0
def choose_event_location(patient_id, appointment_id):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT ]
    if not session['role'] in authorized_roles:
        return redirect(url_for('index'))
    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    return render_template('choose_event_location.html',
                                            patient=patient,
                                            appointment=appointment)
Example #12
0
def make_payment(patient_id, appointment_id):
    patient, appointment = checks.get_patient_appointment(patient_id, appointment_id)
    payment_form = PatientPaymentForm(request.form)
    payment_form.mean_id.choices = [
        (mean.id, mean.odontux_name)
        for mean in meta.session.query(compta.PaymentType).filter(compta.PaymentType.active.is_(True)).all()
    ]

    if request.method == "POST" and payment_form.validate():
        # get the gnucash mean_account_odontux_asset name
        mean = meta.session.query(compta.PaymentType).filter(compta.PaymentType.id == payment_form.mean_id.data).one()
        # create gnucash instance in advance for not having problem after
        # payment registered in odontux
        gcpayment = gnucash_handler.GnuCashPayment(patient_id, patient.dentist_id)

        pdf_out = make_payment_receipt(patient_id, appointment_id, payment_form, mean)
        if not pdf_out:
            return render_template(
                "make_payment.html", patient=patient, appointment=appointment, payment_form=payment_form
            )
        filename = md5.new(pdf_out).hexdigest()
        with open(os.path.join(app.config["DOCUMENT_FOLDER"], filename), "w") as f:
            f.write(pdf_out)
        file_values = {"md5": filename, "file_type": constants.FILE_RECEIPT, "mimetype": "application/pdf"}
        new_file = meta.session.query(documents.Files).filter(documents.Files.md5 == filename).one_or_none()
        if not new_file:
            new_file = documents.Files(**file_values)
            meta.session.add(new_file)
            meta.session.commit()

        receipt_values = {
            "patient_id": patient_id,
            "mean_id": payment_form.mean_id.data,
            "receipt_id": new_file.id,
            "amount": payment_form.amount.data,
            "comments": payment_form.comments.data,
            "cashin_date": datetime.date.today(),
        }
        new_payment = compta.Payment(**receipt_values)
        meta.session.add(new_payment)
        meta.session.commit()

        # Record payment in gnucash and create bill:
        gcpayment.add_payment(new_payment.mean_id, new_payment.amount, new_payment.cashin_date)

        return redirect(url_for("list_acts", patient_id=patient_id, appointment_id=appointment_id))

    if request.method == "GET":
        if patient.balance() < 0:
            payment_form.amount.data = abs(patient.balance())
        else:
            payment_form.amount.data = 0

    payment_form.patient_id.data = patient.id
    return render_template("make_payment.html", patient=patient, appointment=appointment, payment_form=payment_form)
Example #13
0
def apply_payment_to_gesture(patient_id, gesture_id):
    authorized_roles = [
        constants.ROLE_DENTIST,
        constants.ROLE_NURSE,
        constants.ROLE_ASSISTANT,
        constants.ROLE_SECRETARY,
    ]
    if session["role"] not in authorized_roles:
        return abort(403)
    appointment_cotation = (
        meta.session.query(act.AppointmentCotationReference)
        .filter(act.AppointmentCotationReference.id == gesture_id)
        .one()
    )
    patient, appointment = checks.get_patient_appointment(patient_id=patient_id)
    if patient.balance() < 0:
        return redirect(url_for("list_acts", patient_id=patient_id))
    if appointment_cotation.price <= patient.already_paid() - patient.gestures_marked_as_paid():
        appointment_cotation.is_paid = True
        meta.session.commit()

        gestures_in_invoice = (
            meta.session.query(act.AppointmentCotationReference)
            .filter(act.AppointmentCotationReference.invoice_id == appointment_cotation.invoice_id)
            .all()
        )

        if all([gesture.is_paid for gesture in gestures_in_invoice]):
            invoice = gnucash_handler.GnuCashInvoice(
                patient.id, appointment_cotation.appointment_id, None, invoice_id=appointment_cotation.invoice_id
            )
            apply_payment_to_invoice = invoice.apply_payment()

            gestures_id_in_bill = ""
            # create a bill for user:
            for index, gesture in enumerate(gestures_in_invoice):
                if index == 0:
                    gestures_id_in_bill = str(gesture.id)
                else:
                    gestures_id_in_bill = gestures_id_in_bill + "," + str(gesture.id)
            return redirect(
                url_for(
                    "choose_gestures_in_bill",
                    patient_id=patient_id,
                    appointment_id=appointment_cotation.appointment_id,
                    gestures_id_in_bill=gestures_id_in_bill,
                )
            )
            #####

    return redirect(url_for("list_acts", patient_id=patient_id))
Example #14
0
def patient_payments(patient_id, appointment_id=0):

    patient, appointment = checks.get_patient_appointment(patient_id, appointment_id)
    payments = meta.session.query(compta.Payment).filter(compta.Payment.patient_id == patient_id).all()
    bills = meta.session.query(statements.Bill).filter(statements.Bill.patient_id == patient_id).all()
    currency_symbol = constants.CURRENCY_SYMBOL
    return render_template(
        "patient_payments.html",
        patient=patient,
        appointment=appointment,
        payments=payments,
        bills=bills,
        currency_symbol=currency_symbol,
    )
Example #15
0
def show_tooth(patient_id, appointment_id, tooth_codename):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE ]
    if session['role'] not in authorized_roles:
        return redirect(url_for('index'))

    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    tooth = ( 
        meta.session.query(teeth.Tooth)
            .filter(teeth.Tooth.patient_id == patient_id,
                    teeth.Tooth.codename == tooth_codename
            )
            .one_or_none()
    )
    if tooth:
        gum = (
            meta.session.query(teeth.Gum)
                .filter(teeth.Gum.id == tooth.id).one()
        )
    # we want that appears only events that occured before the 
    # actual_appointment we're in.
    all_event_type = with_polymorphic(teeth.Event, '*')
    events = (
        meta.session.query(all_event_type)
            .filter(
                teeth.Event.tooth_id == tooth.id,
                teeth.Event.appointment_id.in_(
                    meta.session.query(schedule.Agenda.appointment_id)
                        .filter(
                            schedule.Agenda.starttime <=
                                        appointment.agenda.starttime
                        )
                    )
            )
            .join(schedule.Appointment, schedule.Agenda)
            .order_by(
                schedule.Agenda.starttime.desc(),
                teeth.Event.location
            )
            .all()
        )
    document_form = DocumentForm(request.form)
    return render_template('show_tooth.html', patient=patient,
                                              appointment=appointment,
                                              tooth=tooth,
                                              gum=gum,
                                              constants=constants,
                                              events=events,
                                              document_form=document_form)
Example #16
0
def patient_appointment(appointment_id):
    """
    """
    authorized_roles = [ constants.ROLE_DENTIST ]
    if session['role'] not in authorized_roles:
        return redirect(url_for('index'))
    patient, appointment = checks.get_patient_appointment(
                                                appointment_id=appointment_id)

    acts = checks.get_patient_acts(patient.id, appointment.id,
                [ act.AppointmentCotationReference.anatomic_location ]
                )
    return render_template("patient_appointment.html",
                            patient=patient,
                            appointment=appointment,
                            acts=acts)
Example #17
0
def list_teeth(patient_id, appointment_id=None):
    authorized_roles = [ constants.ROLE_DENTIST ]
    if session['role'] not in authorized_roles:
        return redirect(url_for('index'))
    
    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    teeth = []
    for tooth in patient.teeth:
        teeth.append( ( tooth.id, 
                        constants.ANATOMIC_LOCATION_TEETH[tooth.codename][1], 
                        constants.TOOTH_STATES[tooth.state][0], 
                        tooth.surveillance )
                    )
    return render_template('list_teeth.html', patient=patient, 
                            appointment=appointment, teeth=teeth)
Example #18
0
def choose_drugs_to_prescribe(patient_id, appointment_id, drug_list=''):
    """
        session['prescription'] = [ drug_id_1, drug_id_2 ]
    """
    authorized_roles = [ constants.ROLE_DENTIST ]
    if session['role'] not in authorized_roles:
        return abort(403)
    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    drugs_prescribed = []
    if drug_list:
        drugs_prescribed = [ drug_id for drug_id in drug_list.split(",") ]

    prescribed = (
        meta.session.query(medication.DrugPrescribed)
            .filter(medication.DrugPrescribed.id.in_(drugs_prescribed))
            .join(medication.DrugFamily)
            .order_by(
                medication.DrugFamily.name,
                medication.DrugPrescribed.molecule)
            .all()
    )

    other_drugs = (
        meta.session.query(medication.DrugPrescribed)
            .filter(~medication.DrugPrescribed.id.in_(drugs_prescribed))
            .join(medication.DrugFamily)
            .order_by(
                medication.DrugFamily.name,
                medication.DrugPrescribed.molecule)
            .all()
    )
   
    if drug_list:
        return render_template('choose_drugs_to_prescribe.html', 
                                        patient=patient,
                                        appointment=appointment,
                                        prescribed=prescribed,
                                        other_drugs=other_drugs,
                                        drug_list=drug_list)

    return render_template('choose_drugs_to_prescribe.html', 
                                        patient=patient,
                                        appointment=appointment,
                                        prescribed=prescribed,
                                        other_drugs=other_drugs)
Example #19
0
def list_appointments(patient_id):
    # Go to index if the admin tries to look at appointments
    # or if we aren't in a patient file.
    if session['role'] == constants.ROLE_ADMIN:
        return abort(403)
    
    # Get the patient in database, and the list of his appointments.
    patient, appointment = checks.get_patient_appointment(
                                                        patient_id=patient_id)
    appointments = ( meta.session.query(schedule.Appointment)
                        .filter(schedule.Appointment.patient_id == patient_id)
                        .join(schedule.Agenda)
                        .order_by(schedule.Agenda.starttime.desc())
                        .all()
    )
    return render_template("list_patient_appointments.html",
                            patient=patient,
                            appointment=appointment,
                            appointments=appointments)
Example #20
0
def add_materio_vigilance_to_clinic_report(appointment_id):
    patient, appointment = checks.get_patient_appointment(
                                    appointment_id=appointment_id)
    material_form = ChooseMaterialForReportForm(request.form)
    
    materials_for_materio_vigilance = (
        meta.session.query(assets.Material)
            .filter(
                assets.Material.end_of_use.is_(None),
                assets.Material.end_use_reason ==
                                    constants.END_USE_REASON_IN_USE_STOCK,
                assets.Material.start_of_use.isnot(None),
                ~assets.Material.id.in_(
                    meta.session.query(
                        traceability.MaterioVigilance.material_id)
                        .filter(traceability.MaterioVigilance.appointment_id ==
                                                                appointment.id
                    )
                )
            )
            .join(assets.MaterialCategory, act.Specialty)
            .order_by(
                act.Specialty.name,
                assets.MaterialCategory.commercial_name,
                assets.MaterialCategory.brand )
            .all()
    )
    material_form.material_id.choices = [ 
        ( material.id, material.asset_category.commercial_name + " " +
                        material.asset_category.brand ) for material in
                        materials_for_materio_vigilance 
    ]

    if material_form.validate():
        material = ( meta.session.query(assets.Material)
                        .get(material_form.material_id.data) 
        )
        materio_vigilance = add_to_materio_vigilance(appointment_id, 
                                material.asset_category.automatic_decrease, 
                                                                    material)

    return redirect(url_for('view_clinic_report', 
                                            appointment_id=appointment_id))
Example #21
0
def portal_certificate(patient_id, appointment_id):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY]
    if session['role'] not in authorized_roles:
        return abort(403)

    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    certifs = ( meta.session.query(certificates.Certificate)
                    .filter(certificates.Certificate.patient_id == patient_id)
    )
    presences = ( certifs
                .filter(certificates.Certificate.certif_type ==\
                                                    constants.FILE_PRESENCE)
                .join(schedule.Appointment, schedule.Agenda)
                .order_by(schedule.Agenda.starttime.desc())
                .all()
    )
    cessations = ( certifs
                .filter(certificates.Certificate.certif_type ==\
                                                    constants.FILE_CESSATION)
                .join(schedule.Appointment, schedule.Agenda)
                .order_by(schedule.Agenda.starttime.desc())
                .all()
    )
    requisitions = ( certifs
                .filter(certificates.Certificate.certif_type ==\
                                                    constants.FILE_REQUISITION)
                .join(schedule.Appointment, schedule.Agenda)
                .order_by(schedule.Agenda.starttime.desc())
                .all()
    )
    return render_template('list_certificates.html',
                                patient=patient,
                                appointment=appointment,
                                presences=presences,
                                cessations=cessations,
                                requisitions=requisitions)
Example #22
0
def add_event_tooth_located(patient_id, appointment_id):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT ]
    if session['role'] not in authorized_roles:
        return abort(403)

    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    ( tooth_form, event_form, crown_event_form, 
        root_event_form, periodontal_event_form,
        tooth_model_form ) = get_event_forms(appointment)

    if ( request.method == 'POST' and event_form.validate() 
                                                and tooth_form.validate() ):

        def _update_tooth_datas(tooth, tooth_values):
            tooth.state = tooth_values['state']
            tooth.surveillance = tooth_values['surveillance']
            meta.session.commit()
            
        teeth_to_add = get_teeth_list(event_form.teeth.data)               
        
        tooth_values = {
            'state': tooth_form.choose_tooth_state.data,
            'surveillance': tooth_form.surveillance.data,
        }
        values = {
            'appointment_id': event_form.appointment_id.data,
            'description': event_form.description.data,
            'comment': event_form.comment.data,
            'color': event_form.color.data,
            'location': event_form.location.data,
            'state': tooth_form.choose_tooth_state.data,
        }

        if ( event_form.location.data == 
                                        constants.TOOTH_EVENT_LOCATION_TOOTH ):
            
            for tooth_codename in teeth_to_add:
                tooth = get_patient_tooth(patient_id, tooth_codename)
                _update_tooth_datas(tooth, tooth_values)
                values['tooth_id'] = tooth.id
                new_tooth_event = teeth.ToothEvent(**values)
                meta.session.add(new_tooth_event)
                meta.session.commit()

        elif ( event_form.location.data == 
                                        constants.TOOTH_EVENT_LOCATION_CROWN
                                            and crown_event_form.validate() ):
            crown_values = {
                'state': crown_event_form.choose_crown_state.data,
                'tooth_shade': crown_event_form.tooth_shade.data,
                }
            values.update(crown_values)
            for tooth_codename in teeth_to_add:
                tooth = get_patient_tooth(patient_id, tooth_codename)
                # working with event_values for state !
                _update_tooth_datas(tooth, tooth_values)
                values['tooth_id'] = tooth.id
                for side in crown_sides():
                    values[side] = getattr(crown_event_form, side).data
                new_crown_event = teeth.CrownEvent(**values)
                meta.session.add(new_crown_event)
                meta.session.commit()

        elif ( event_form.location.data == 
                                            constants.TOOTH_EVENT_LOCATION_ROOT
                                            and root_event_form.validate() ):
            root_values = {
                'state': root_event_form.choose_root_state.data,
                }
            values.update(root_values)
            for tooth_codename in teeth_to_add:
                tooth = get_patient_tooth(patient_id, tooth_codename)
                # working with event_values for state !
                _update_tooth_datas(tooth, tooth_values)
                values['tooth_id'] = tooth.id
                for root_canal in root_canals():
                    values[root_canal] =\
                                    getattr(root_event_form, root_canal).data
                new_root_event = teeth.RootCanalEvent(**values)
                meta.session.add(new_root_event)
                meta.session.commit()
        
        elif ( event_form.location.data == 
                                    constants.TOOTH_EVENT_LOCATION_PERIODONTAL
                                    and periodontal_event_form.validate() ):
            periodontal_values = {
                'furcation': periodontal_event_form.furcation.data,
                'recession': periodontal_event_form.recession.data,
                'pocket_depth': periodontal_event_form.pocket_depth.data,
                }
            values.update(periodontal_values)
            del values['state'] # As there is no "state" in PeriodontalEvent
            for tooth_codename in teeth_to_add:
                tooth = get_patient_tooth(patient_id, tooth_codename)
                gum = get_patient_gum(patient_id, tooth_codename)
                # updating gum table
                gum.state = periodontal_event_form.choose_periodontal_state.data
                gum.bleeding = periodontal_event_form.bleeding.data
                # working with event_values for state !
                _update_tooth_datas(tooth, tooth_values)
                values['tooth_id'] = tooth.id
                for site in periodontal_locations():
                    values[site] = getattr(periodontal_event_form, site).data
                new_periodontal_event = teeth.PeriodontalEvent(**values)
                meta.session.add(new_periodontal_event)
                meta.session.commit()

        return redirect(url_for('add_event_tooth_located',
                                patient_id=patient_id,
                                appointment_id=appointment_id))

    if request.method == 'POST':
        clear_form = False
    else:
        clear_form = True
    return render_template('add_event_tooth_located.html',
                    patient=patient, appointment=appointment,
                    tooth_form=tooth_form,
                    event_form=event_form,
                    crown_event_form=crown_event_form,
                    root_event_form=root_event_form,
                    periodontal_event_form=periodontal_event_form,
                    clear_form=clear_form)
Example #23
0
def add_cg_to_cr(appointment_id, clinic_gesture_id, anatomic_location):
    """
        anatomic_location = int.
        * Create a clinic_report entry with a clinic_gesture.
        * Add material in use from model_material_category from clinic_gesture
        to MaterioVigilance and update quantities
        * If clinic_gesture as a model_event, create the event adapted
    """
    def _needs_redondance(appointment, material, mat_cg_ref):

        number_of_same_cg_in_appointment = [ cr.clinic_gesture for cr in
                                            appointment.clinic_reports 
            if cr.clinic_gesture_id == mat_cg_ref.clinic_gesture_id
        ]
        if not ( ( len(number_of_same_cg_in_appointment) - 1 ) % 
                                mat_cg_ref.enter_in_various_gestures ):
            return True
        else:
            return False

    patient, appointment = checks.get_patient_appointment(
                                                appointment_id=appointment_id)
    clinic_gesture = ( meta.session.query(act.ClinicGesture)
                        .filter(act.ClinicGesture.id == clinic_gesture_id )
                        .one()
    )
    ##
    ## Create new clinic_report entry
    values = {
        'appointment_id': appointment_id,
        'clinic_gesture_id': clinic_gesture_id,
        'anatomic_location': int(anatomic_location),
        'duration': clinic_gesture.duration,
    }
    new_clinic_report = act.ClinicReport(**values)
    meta.session.add(new_clinic_report)
    # or: appointment.clinic_reports.append(new_clinic_report)
    try:
        meta.session.commit()
    except sqlalchemy.exc.IntegrityError:
        meta.session.rollback()

    appointment.clinic_reports.reorder()
    meta.session.commit()
    
    ##
    ## Update Material and MaterioVigilance
    for mat_cg_ref in new_clinic_report.clinic_gesture.materials:
        
        material_used = cost.get_material_used(mat_cg_ref.id)
        
        if ( _needs_redondance(appointment, material_used, mat_cg_ref)
            and material_used ):

            materio_vigilance = add_to_materio_vigilance(appointment_id, 
                                    mat_cg_ref.mean_quantity, material_used)
            new_clinic_report.materio_vigilance.append(materio_vigilance)
            meta.session.commit()
    
    ##
    ## Create event 
    if clinic_gesture.event_model_id:
        event_model = ( meta.session.query(model_teeth.EventModel)
            .filter(model_teeth.EventModel.id == clinic_gesture.event_model_id )
            .one()
        )
        tooth = teeth.get_patient_tooth(appointment.patient_id, 
                                                    int(anatomic_location))
        tooth.state = event_model.tooth_state
        tooth.surveillance = event_model.surveillance
        values = {
            'appointment_id': appointment_id,
            'tooth_id': tooth.id,
            'location': event_model.location,
            'state': event_model.state,
            'description': event_model.description,
            'comment': event_model.comment,
            'color': event_model.color,
        }
        if event_model.location == constants.TOOTH_EVENT_LOCATION_PERIODONTAL :
            pass
        elif event_model.location == constants.TOOTH_EVENT_LOCATION_TOOTH:
            pass
        elif event_model.location == constants.TOOTH_EVENT_LOCATION_CROWN:
            new_crown_event = model_teeth.CrownEvent(**values)
            meta.session.add(new_crown_event)
            meta.session.commit()
            for att in [ 'state', 'is_occlusal', 'is_buccal', 'is_lingual',
                    'is_mesial', 'is_distal', 'tooth_shade' ] :
                setattr(new_crown_event, att, getattr(event_model, att))
        elif event_model.location == constants.TOOTH_EVENT_LOCATION_ROOT:
            new_root_event = model_teeth.RootCanalEvent(**values)
            meta.session.add(new_root_event)
            meta.session.commit()
            for att in [ 'state', 'is_central', 'is_buccal', 'is_lingual',
                'is_mesial', 'is_distal', 'is_mesio_buccal', 'is_disto_buccal',
                'is_mesio_lingual', 'is_disto_lingual', 'is_mesio_buccal_2' ] :
                setattr(new_root_event, att, getattr(event_model, att))
        meta.session.commit()
 
    return new_clinic_report
Example #24
0
def update_clinic_report(appointment_id):

    patient, appointment = checks.get_patient_appointment(
                                                appointment_id=appointment_id)
    clinic_report_form = ClinicReportForm(request.form)
    if clinic_report_form.validate():
        for entry in clinic_report_form.clinic_gestures.entries:
            if entry.old_duration.data != entry.new_duration.data:
                clinic_report = ( meta.session.query(act.ClinicReport)
                    .filter(act.ClinicReport.id == 
                                        int(entry.clinic_report_id.data) )
                    .one()
                )
                clinic_report.duration = datetime.timedelta(
                        seconds=int(entry.new_duration.data) * 60 )
                meta.session.commit()
                
        for entry in clinic_report_form.materials_used.entries:
            if entry.new_quantity_used.data is None:
                entry.new_quantity_used.data = 0
            if Decimal(entry.old_quantity_used.data) ==\
                                                entry.new_quantity_used.data:
                continue
            material = ( 
                meta.session.query(assets.Material)
                    .filter(assets.Material.id == int(entry.material_id.data))
                    .one()
            )
            materio_vigilance = (
                meta.session.query(traceability.MaterioVigilance)
                    .filter(
                        traceability.MaterioVigilance.appointment_id == 
                                                                appointment.id,
                        traceability.MaterioVigilance.material_id == 
                                                                material.id)
                    .one()
            )

            delta_quantity = Decimal(entry.old_quantity_used.data) -\
                                                entry.new_quantity_used.data
            materio_vigilance.quantity_used -= delta_quantity
            material.actual_quantity += delta_quantity
            meta.session.commit()
            # Case the material was marked as terminated, but finally there is
            # some left :
            if ( material.end_of_use == appointment.agenda.endtime.date()
                    and material.end_use_reason == 
                                        constants.END_USE_REASON_NATURAL_END
                    and material.actual_quantity > 0 ):
                material.end_of_use = None
                material.end_use_reason = constants.END_USE_REASON_IN_USE_STOCK
                meta.session.commit()

            # Case material terminate :
            if material.actual_quantity <= 0:
                material.end_of_use = appointment.agenda.endtime.date()
                material.end_use_reason = constants.END_USE_REASON_NATURAL_END
                meta.session.commit()

    return redirect(url_for('view_clinic_report', 
                                                appointment_id=appointment.id))
Example #25
0
def make_bill(patient_id, appointment_id, gestures_id_in_bill):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY ]
    if session['role'] not in authorized_roles:
        return abort(403)
    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    gestures_in_bill = ( 
        meta.session.query(act.AppointmentCotationReference)
        .filter(act.AppointmentCotationReference.id.in_( 
                [ int(gid) for gid in gestures_id_in_bill.split(",") ] ) )
        .all()
    )
    bill_form = BillForm(request.form)

    if request.method == 'GET':
        for gesture in gestures_in_bill:
            gesture_form = GestureForm(request.form)
            gesture_form.gesture_id = gesture.id
            gesture_form.gesture_name = gesture.gesture.name
            gesture_form.date =\
                        gesture.appointment.agenda.starttime.date().isoformat()
            gesture_form.anatomic_location = gesture.anatomic_location
            gesture_form.price = gesture.price
            bill_form.gestures.append_entry(gesture_form)

    pdf_out = make_invoice_payment_bill(patient_id, 
                                        gestures_in_bill[-1].appointment_id,
                                        bill_form)
 
    if request.method == 'POST' and bill_form.validate():
        if 'update' in request.form:
            return render_template('make_bill.html', patient=patient,
                                    appointment=appointment,
                                    constants=constants,
                                    bill_form=bill_form,
                                    gestures_id_in_bill=gestures_id_in_bill,
                                    pdf_out=b64encode(pdf_out))
        elif 'preview' in request.form:
            response = make_response(pdf_out)
            response.mimetype = 'application/pdf'
            return response

        elif 'save_print' in request.form:
            response = make_response(pdf_out)
            response.mimetype = 'application/pdf'
            filename = md5.new(pdf_out).hexdigest()

            with open(os.path.join(
                        app.config['DOCUMENT_FOLDER'], filename), 'w') as f:
                f.write(pdf_out)

            file_values = {
                'md5': filename,
                'file_type': constants.FILE_BILL,
                'mimetype': 'application/pdf',
            }
            new_file = documents.Files(**file_values)
            meta.session.add(new_file)
            meta.session.commit()

            bill_values = {
                'patient_id': patient_id,
                'appointment_id': gestures_in_bill[-1].appointment_id,
                'dentist_id': appointment.dentist_id,
                'type': constants.FILE_BILL,
                'file_id': new_file.id,
            }
            new_bill = statements.Bill(**bill_values)
            meta.session.add(new_bill)
            meta.session.commit()

            for gesture in bill_form.gestures:
                values = {
                    'bill_id': new_bill.id,
                    'appointment_cotation_id': int(gesture.gesture_id.data),
                }
                new_gesture =\
                    statements.BillAppointmentCotationReference(**values)
                meta.session.add(new_gesture)
                meta.session.commit()

            return response

    return render_template('make_bill.html', patient=patient,
                                    appointment=appointment,
                                    constants=constants,
                                    bill_form=bill_form,
                                    gestures_id_in_bill=gestures_id_in_bill)
Example #26
0
def view_clinic_report(appointment_id):
    patient, appointment = checks.get_patient_appointment( 
                                            appointment_id=appointment_id)

    cotation_form = ChooseCotationForReportForm(request.form)
    cotation_form.cotation_id.choices = [
        ( cotation.id, cotation.gesture.name +  " " + 
            cotation.healthcare_plan.name) for cotation in
         meta.session.query(act.Cotation)
            .filter(act.Cotation.healthcare_plan_id.in_(
                                            [ hc.id for hc in patient.hcs ] )
            )
            .join(act.Gesture, act.Specialty, act.HealthCarePlan)
            .order_by(act.Specialty.name,
                        act.Gesture.name,
                        act.HealthCarePlan.name.desc())
            .all()
    ]
    cg_form = ChooseClinicGestureForReportForm(request.form)
    cg_form.clinic_gesture_id.choices = [
        ( cg.id, cg.specialty.name[0:3] + " " + cg.name ) for cg in
            meta.session.query(act.ClinicGesture)
                .filter(act.ClinicGesture.before_first_patient.is_(False),
                        act.ClinicGesture.after_last_patient.is_(False),
                        act.ClinicGesture.before_each_appointment.is_(False),
                        act.ClinicGesture.after_each_appointment.is_(False)
                )
                .join(act.Specialty)
                .order_by(act.Specialty.name, act.ClinicGesture.name )
                .all()
    ]
    clinic_report_form = ClinicReportForm(request.form)

    clinic_gestures = [ clinic_report for clinic_report in 
                            sorted(appointment.clinic_reports,
                                key=lambda clinic_report: 
                                    clinic_report.sequence) 
    ]

    # Case dentist_fees and hour_cost isn't provided yet:
    if not appointment.dentist_fees:
        appointment.dentist_fees = ( 
            meta.session.query(act.HealthCarePlanUserReference.hour_fees)
                .filter(
                    act.HealthCarePlanUserReference.user_id == 
                                                        appointment.dentist_id,
                    act.HealthCarePlanUserReference.healthcare_plan_id.in_(
                        [ hcp.id for hcp in appointment.patient.hcs ] )
                )
                .order_by(act.HealthCarePlanUserReference.hour_fees)
                .first()
        )
        if not appointment.dentist_fees:
            appointment.dentist_fees = 1

        meta.session.commit()

    if not appointment.hour_cost:
        appointment.hour_cost = round(cost.get_hourly_operational_cost(), 2)
        meta.session.commit()

    # In case this day is the first where happens something, we add in this 
    # clinic report the material that is used every morning and every night 
    # before opening and closing the dental_unit
    # We need to check this first.
    # TODO Add a verification if material found is only materials use in an
    # autoclave cycle because it doesn't count
    material_used_this_day = ( 
        meta.session.query(traceability.MaterioVigilance)
        .filter(
            traceability.MaterioVigilance.appointment_id.in_(
                meta.session.query(schedule.Agenda.appointment_id)
                    .filter(
                        cast(schedule.Agenda.starttime, Date) == 
                                        appointment.agenda.starttime.date(),
                        schedule.Agenda.dental_unit_id ==
                                                    appointment.dental_unit_id
                    )
            )
        )
        .all()
    )
    # In case no material has been marqued used in this appointment, we now add
    # the minimum material used in each appointment
    # This query is made before adding eventual "material before first patient
    # TODO Add a verification if material found is only materials use in an
    # autoclave cycle because it doesn't count
    material_each_appointment = ( 
        meta.session.query(traceability.MaterioVigilance)
        .filter(traceability.MaterioVigilance.appointment_id == appointment.id)
        .all()
    )

    if not material_used_this_day:
        cg_every_work_day = (  meta.session.query(act.ClinicGesture)
            .filter(or_(
                act.ClinicGesture.before_first_patient.is_(True),
                act.ClinicGesture.after_last_patient.is_(True)
                ) )
            .all()
        )
        for cg in cg_every_work_day:
            for mat_cg_ref in cg.materials:
                material_used = cost.get_material_used(mat_cg_ref.id)
                opening_materio_vigilance = add_to_materio_vigilance(
                    appointment.id, mat_cg_ref.mean_quantity, material_used)

    if not material_each_appointment:
        cg_all_appointment = ( meta.session.query(act.ClinicGesture)
            .filter(or_(
                act.ClinicGesture.before_each_appointment.is_(True),
                act.ClinicGesture.after_each_appointment.is_(True)
                ) )
            .all()
        )
        for cg in cg_all_appointment:
            for mat_cg_ref in cg.materials:
                material_used = cost.get_material_used(mat_cg_ref.id)
                materio_vigilance_appointment = add_to_materio_vigilance(
                    appointment.id, mat_cg_ref.mean_quantity, material_used)

    material_form = ChooseMaterialForReportForm(request.form)
    
    materials_for_materio_vigilance = (
        meta.session.query(assets.Material)
            .filter(
                assets.Material.end_of_use.is_(None),
                assets.Material.end_use_reason ==
                                    constants.END_USE_REASON_IN_USE_STOCK,
                assets.Material.start_of_use.isnot(None),
                ~assets.Material.id.in_(
                    meta.session.query(
                        traceability.MaterioVigilance.material_id)
                        .filter(traceability.MaterioVigilance.appointment_id ==
                                                                appointment.id
                    )
                )
            )
            .join(assets.MaterialCategory, act.Specialty)
            .order_by(
                act.Specialty.name,
                assets.MaterialCategory.commercial_name,
                assets.MaterialCategory.brand )
            .all()
    )
    material_form.material_id.choices = [ 
        ( material.id, material.asset_category.commercial_name + " " +
                        material.asset_category.brand ) for material in
                        materials_for_materio_vigilance 
    ]

    # only appears cotation that were administraly officially indentified,
    # by a single clinic gesture in the global gesture repair.
    cotations = [ cot for cot in sorted(appointment.administrative_gestures,
                                key=lambda cot: (
                                    cot.gesture.name,
                                    cot.anatomic_location ) )
    ]
    
    for mat_vig in sorted(appointment.materio_vigilance, key=lambda mat_vig:(
                        mat_vig.material.asset_category.asset_specialty.name,
                            mat_vig.material.asset_category.commercial_name) ):

        mat_vig_form = MaterioVigilanceForm(request.form)
        mat_vig_form.material_id = mat_vig.material_id
        mat_vig_form.old_quantity_used = mat_vig.quantity_used
        mat_vig_form.new_quantity_used = mat_vig.quantity_used
        mat_vig_form.material_data = (
            mat_vig.material.asset_category.commercial_name + " | " +
            str(mat_vig.material.actual_quantity) + " " +
            constants.UNITIES[mat_vig.material.asset_category.unity][1] )

        clinic_report_form.materials_used.append_entry(mat_vig_form)

    for clinic_report in sorted(appointment.clinic_reports, 
                                    key=lambda clinic_report: (
                                        clinic_report.anatomic_location,
                                        clinic_report.sequence )
                                                                        ):
        
        hour_duration = clinic_report.duration.seconds / 3600 * 60
        minute_duration = clinic_report.duration.seconds % 3600 / 60
        cg_duration_form = ClinicGestureDurationForm(request.form)
        cg_duration_form.clinic_report_id = clinic_report.id
        cg_duration_form.clinic_gesture_id = clinic_report.clinic_gesture_id
        cg_duration_form.anatomic_location = clinic_report.anatomic_location
        cg_duration_form.old_duration = str(hour_duration + minute_duration)
        cg_duration_form.new_duration = hour_duration + minute_duration
        cg_duration_form.clinic_gesture_data =\
                                            clinic_report.clinic_gesture.name

        clinic_report_form.clinic_gestures.append_entry(cg_duration_form)

    return render_template('view_clinic_report.html', 
                            patient=patient,
                            appointment=appointment,
                            cotations=cotations,
                            clinic_report_form=clinic_report_form,
                            cotation_form=cotation_form,
                            cg_form=cg_form,
                            material_form=material_form,
                            constants=constants)
Example #27
0
def create_quote_proposition(patient_id, appointment_id, quotes_id=''):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT ]
    if session['role'] not in authorized_roles:
        return abort(403)
    patient, appointment = checks.get_patient_appointment(patient_id,
                                                                appointment_id)
    if not quotes_id:
        quotes = ( 
            meta.session.query(statements.Quote)
                .filter(statements.Quote.appointment_id == appointment_id,
                        statements.Quote.file_id.is_(None) )
                .all()
        )
        for quote in quotes:
            if not quotes_id:
                quotes_id = str(quote.id)
                continue
            quotes_id = quotes_id + "," + str(quote.id)
    else:
        quotes = ( meta.session.query(statements.Quote)
                    .filter(statements.Quote.id.in_(
                            [ int(i) for i in quotes_id.split(",") ] ))
                    .all()
        )
    quote_form = QuotePropositionForm(request.form)
    quote_form.healthcare_plan_id.choices = [ (hcp.id, hcp.name) for hcp in
        meta.session.query(act.HealthCarePlan)
        .filter(act.HealthCarePlan.id.in_(patient.healthcare_plans_id))
        .all() ]
    quote_gesture_form = QuoteGestureForm(request.form)

    if request.method == 'POST':
        if ( 'proposition-0-add_gesture' in request.form
                                            and quote_form.validate() ):
            quote_gesture_form.cotation_id =\
                                quote_form.proposition[0].cotation_id.data
            quote_gesture_form.anatomic_location =\
                        quote_form.proposition[0].anatomic_location.data
            quote_gesture_form.gesture_code =\
                                quote_form.proposition[0].gesture_code.data
            quote_gesture_form.gesture_name =\
                                quote_form.proposition[0].gesture_name.data
            quote_gesture_form.price =\
                                quote_form.proposition[0].price.data
            quote_gesture_form.appointment_number =\
                        quote_form.proposition[0].appointment_number.data
            quote_form.proposition.append_entry(quote_gesture_form)
           
        elif 'remove_last' in request.form:
            quote_form.proposition.pop_entry()

        elif 'add_proposition' in request.form:
            if ( len(quote_form.proposition.entries) == 0 or
                len(quote_form.proposition.entries) == 1 and
                not quote_form.proposition.entries[0].gesture_code.data ):
                return redirect(url_for('create_quote_proposition',
                                            patient_id=patient_id,
                                            appointment_id=appointment_id,
                                            quotes_id=quotes_id))

            # create new proposition of quote
            if quote_form.treatment_duration.data:
                if quote_form.duration_unity.data == 'month':
                    treatment_duration =quote_form.treatment_duration.data * 30
                elif quote_form.duration_unity.data == 'week':
                    treatment_duration = quote_form.treatment_duration.data * 7
                else:
                    treatment_duration = quote_form.treatment_duration.data
                treatment_duration =datetime.timedelta(days=treatment_duration)
            else:
                treatment_duration = None
            values = {
                'patient_id': patient_id,
                'dentist_id': appointment.dentist_id,
                'appointment_id': appointment_id,
                'type': constants.FILE_QUOTE,
                'validity': appointment.agenda.starttime +\
                datetime.timedelta(days=quote_form.validity.data * 30),
                'treatment_duration': treatment_duration,
            }
            new_proposition_quote = statements.Quote(**values)
            meta.session.add(new_proposition_quote)
            meta.session.commit()
            # insert gesture in this proposition of quote
            while quote_form.proposition.entries:
                entry = quote_form.proposition.pop_entry().data
                if not entry['cotation_id']:
                    continue
                gesture = ( meta.session.query(act.Gesture)
                    .filter(act.Gesture.code == entry['gesture_code'],
                            act.Gesture.cotations.any(
                                act.Cotation.id == entry['cotation_id'])
                    )
                    .one_or_none()
                )
                if not gesture:
                    continue
                gesture_entry = {
                    'quote_id': new_proposition_quote.id,
                    'cotation_id': entry['cotation_id'],
                    'gesture_id': gesture.id,
                    'anatomic_location': entry['anatomic_location'],
                    'price': entry['price'],
                    'appointment_number': entry['appointment_number'],
                }
                new_gesture_in_proposition =\
                        statements.QuoteGestureReference(**gesture_entry)
                meta.session.add(new_gesture_in_proposition)
                meta.session.commit()
            
            if not quotes_id:
                quotes_id = str(new_proposition_quote.id)
            else:
                quotes_id = quotes_id + "," +\
                                            str(new_proposition_quote.id)
            # We reload the create_quote_proposition to enter in a new GET
            return redirect(url_for('create_quote_proposition',
                                            patient_id=patient_id,
                                            appointment_id=appointment_id,
                                            quotes_id=quotes_id))
        
        elif 'preview' in request.form:
            pdf_out = make_quote(patient_id, appointment_id, quotes)
            response = make_response(pdf_out)
            response.mimetype = 'application/pdf'
            return response
           
        elif 'save_print' in request.form:
            pdf_out = make_quote(patient_id, appointment_id, quotes)
            response = make_response(pdf_out)
            response.mimetype = 'application/pdf'
            filename = md5.new(pdf_out).hexdigest()
            with open(os.path.join(
                        app.config['DOCUMENT_FOLDER'], filename), 'w') as f:
                f.write(pdf_out)

            file_values = {
                'md5': filename,
                'file_type': constants.FILE_QUOTE,
                'mimetype': 'application/pdf',
            }
            file_in_db = ( meta.session.query(documents.Files)
                .filter(documents.Files.md5 == filename)
                .one_or_none()
            )

            new_file = documents.Files(**file_values)
            meta.session.add(new_file)
            meta.session.commit()
            
            for quote in quotes:
                quote.file_id = new_file.id
            meta.session.commit()

            return response
        
        return render_template('create_quote_proposition.html', 
                                                patient=patient,
                                                appointment=appointment,
                                                quotes=quotes,
                                                quote_form=quote_form,
                                                quotes_id=quotes_id)

    quote_form.healthcare_plan_id.data = quote_form.healthcare_plan_id.data
    quote_form.validity.data = constants.QUOTE_VALIDITY
    
    if quotes:
        pdf_out = make_quote(patient_id, appointment_id, quotes)
        pdf_out = b64encode(pdf_out)
        return render_template('create_quote_proposition.html', 
                                                patient=patient,
                                                appointment=appointment,
                                                quotes=quotes,
                                                quote_form=quote_form,
                                                quotes_id=quotes_id,
                                                pdf_out=pdf_out)

    return render_template('create_quote_proposition.html', 
                                                patient=patient,
                                                appointment=appointment,
                                                quotes=quotes,
                                                quote_form=quote_form,
                                                quotes_id=quotes_id,
                                                pdf_out=None)
Example #28
0
def choose_gestures_in_bill(patient_id, appointment_id, 
                                                    gestures_id_in_bill=""):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                        constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY ]
    if session['role'] not in authorized_roles:
        return abort(403)

    patient, appointment = checks.get_patient_appointment(patient_id, 
                                                                appointment_id)
    patient_appointments_id = [ a.id for a in patient.appointments ]
    # get id list of gestures that could be in bill
    gestures_panel = (
        meta.session.query(act.AppointmentCotationReference)
            .join(schedule.Appointment, schedule.Agenda)
            .filter(
                act.AppointmentCotationReference.appointment_id.in_(
                                                    patient_appointments_id),
                act.AppointmentCotationReference.is_paid.is_(True),
                ~act.AppointmentCotationReference.id.in_(
                    meta.session.query(
            statements.BillAppointmentCotationReference.appointment_cotation_id)
                ),
                schedule.Agenda.starttime <= appointment.agenda.starttime
            )
            .order_by(schedule.Agenda.starttime)
            .all()
    )
    gestures_id_panel = [ gesture.id for gesture in gestures_panel ]

    # get id list of gestures that are to be in bill
    if not gestures_id_in_bill:
        gestures_id_in_bill = [ gesture.id for gesture in gestures_panel ]
    else:
        gestures_id_in_bill = [ int(i) for i in gestures_id_in_bill.split(",") ]

    gestures_in_bill = (
        meta.session.query(act.AppointmentCotationReference)
            .filter(
                act.AppointmentCotationReference.id.in_(gestures_id_in_bill))
            .join(schedule.Appointment, schedule.Agenda)
            .order_by(schedule.Agenda.starttime)
            .all()
    )

    # get id list of gestures that won't be in bill
    gestures_not_in_bill = (
        meta.session.query(act.AppointmentCotationReference)
            .filter(
                act.AppointmentCotationReference.id.in_(gestures_id_panel),
                ~act.AppointmentCotationReference.id.in_(gestures_id_in_bill)
            )
            .all()
    )
    
    gestures_id_in_bill = ",".join( [ str(gest.id) 
                                            for gest in gestures_in_bill ] )
    return render_template('choose_gestures_in_bill.html',
                                    patient=patient,
                                    appointment=appointment,
                                    constants=constants,
                                    gestures_in_bill=gestures_in_bill,
                                    gestures_not_in_bill=gestures_not_in_bill,
                                    gestures_id_in_bill=gestures_id_in_bill)
Example #29
0
def add_patient_appointment(body_id, meeting_id=0):
    authorized_roles = [ constants.ROLE_DENTIST, constants.ROLE_NURSE,
                constants.ROLE_ASSISTANT, constants.ROLE_SECRETARY ]
    if session['role'] not in authorized_roles:
        return redirect(url_for('index'))

    agenda_form = AgendaForm(request.form)
    meeting = ( meta.session.query(schedule.Agenda)
                        .filter(schedule.Agenda.id == meeting_id)
                        .one_or_none()
    )
    if meeting:
        day, starthour, startmin, durationhour, durationmin, endhour, endmin =\
            reverse_agenda_handler(meeting.starttime, meeting.endtime)
        agenda_form.meeting_id.data = meeting.id
        agenda_form.day.data = day
        agenda_form.starthour.data = starthour
        agenda_form.startmin.data = startmin
        agenda_form.durationhour.data = durationhour
        agenda_form.durationmin.data = durationmin
        agenda_form.endhour.data = endhour
        agenda_form.endmin.data = endmin
    
    appointment_form = AppointmentForm(request.form)
    appointment_form.dentist_id.choices = [ (user.id, user.firstname + " " 
                                           + user.lastname ) for user in
                            meta.session.query(users.OdontuxUser).filter(
                            users.OdontuxUser.role == constants.ROLE_DENTIST)\
                            .all()
                                          ]
    appointment_form.dental_unit_id.choices = [ 
                    ( dental_unit.id, dental_unit.name ) for dental_unit in
                                meta.session.query(users.DentalUnit).all() ]
    
    if (request.method == 'POST' and agenda_form.validate()
        and appointment_form.validate() ):
        # get the appointment agenda schedule first, to raise exception if 
        # agenda problems
        (starttime, endtime) = agenda_handler(agenda_form.day.data, 
                       agenda_form.starthour.data, agenda_form.startmin.data, 
                       agenda_form.durationhour.data, 
                       agenda_form.durationmin.data,
                       agenda_form.endhour.data, agenda_form.endmin.data)
        # add the appointment infos
        args = { f: getattr(appointment_form, f).data 
                 for f in get_appointment_field_list() }
        new_appointment = schedule.Appointment(**args)
        meta.session.add(new_appointment)
        meta.session.commit()

        # if every thing went fine until now, we just have to add to database
        # agenda data, and we're done.
        if agenda_form.meeting_id.data:
            appointment_in_agenda = (
                meta.session.query(schedule.Agenda)
                    .filter(schedule.Agenda.id == agenda_form.meeting_id.data)
                    .one_or_none()
            )
            if appointment_in_agenda:
                appointment_in_agenda.appointment_id = new_appointment.id
                meta.session.commit()
                return redirect(url_for('patient_appointment', 
                                            appointment_id=new_appointment.id))

#        dentist_fees = ( meta.session.query(act.HealthCarePlanUserReference)
#            .filter(
#                act.HealthCarePlanUserReference.healthcare_plan_id.in_(
#                                            [ hcp.id for hcp in patient.hcs] ),
#                act.HealthCarePlanUserReference.user_id == 
#                                                    appointment.dentist_id )
#                .order_by(act.HealthCarePlanUserReference.hour_fees)
#                .first()
#        )
#        if not dentist_fees:
#            dentist_fees = 1
#
#        hour_cost = cost.get_hourly_operational_cost()
        args = {}
        args['dentist_id'] = new_appointment.dentist_id
        args['date_taker_id'] = new_appointment.dentist_id
        args['dental_unit_id'] = new_appointment.dental_unit_id
        args['appointment_id'] = new_appointment.id
        args['starttime'] = starttime
        args['endtime'] = endtime
#        args['hour_cost'] = hour_cost
#        args['dentist_fees'] = dentist_fees
        new_schedule = schedule.Agenda(**args)
        meta.session.add(new_schedule)
        meta.session.commit()

        return redirect(url_for('patient_appointment',
                                appointment_id=new_appointment.id))

    if not agenda_form.day.data:
        agenda_form.day.data = datetime.date.today()
    
    if session['role'] == constants.ROLE_DENTIST:
        appointment_form.dentist_id.data = session['user_id']
    patient, appointment = checks.get_patient_appointment(patient_id=body_id)
    return render_template('add_patient_appointment.html',
                            patient=patient,
                            agenda_form=agenda_form,
                            appointment_form=appointment_form)
Example #30
0
def add_anamnesis_entry(patient_id, appointment_id, survey_id=None, survey_entry=None):
    authorized_roles = [constants.ROLE_DENTIST]
    if session["role"] not in authorized_roles:
        return redirect(url_for("index"))

    patient, appointment = checks.get_patient_appointment(patient_id, appointment_id)
    anamnesis_form = AnamnesisForm(request.form)
    anamnesis_form.anamnesis_type.choices = [(id, info[0]) for id, info in constants.ANAMNESIS.items()]
    medical_history_form = MedicalHistoryForm(request.form)
    medical_history_form.medical_type.choices = constants.MEDICAL_HISTORIES.items()
    medical_history_form.disease.choices = constants.DISEASES.items()
    addiction_form = AddictionForm(request.form)
    addiction_form.addiction_type.choices = constants.ADDICTIONS.items()
    treatment_form = TreatmentForm(request.form)
    past_surgery_form = PastSurgeryForm(request.form)
    allergy_form = AllergyForm(request.form)
    allergy_form.allergy_type.choices = constants.ALLERGIES.items()
    allergy_form.reaction.choices = [(al_re[0], al_re[1][0]) for al_re in constants.ALLERGIC_REACTIONS.items()]
    oral_hygiene_form = OralHygieneForm(request.form)
    oral_hygiene_form.oral_type.choices = constants.ORAL_HYGIENE.items()

    if survey_entry:
        question = (
            meta.session.query(anamnesis.Question)
            .join(anamnesis.SurveyQuestionsOrder)
            .filter(
                anamnesis.SurveyQuestionsOrder.survey_id == survey_id,
                anamnesis.SurveyQuestionsOrder.position == survey_entry,
            )
            .one_or_none()
        )
        if question:
            anamnesis_form.question_id.data = question.id
    else:
        question = None

    if request.method == "POST" and anamnesis_form.validate():

        anamnesis_values = {
            "patient_id": patient_id,
            "appointment_id": appointment_id,
            "anamnesis_type": anamnesis_form.anamnesis_type.data,
            "alert": anamnesis_form.alert.data,
            "document": anamnesis_form.document.data,
        }
        if question:
            anamnesis_values["question_id"] = question.id
        if survey_entry:
            survey_entry += 1

        if (
            anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_MEDICAL_HISTORY
            and medical_history_form.validate()
        ):
            values = {
                "type": medical_history_form.medical_type.data,
                "disease": medical_history_form.disease.data,
                "name": medical_history_form.denomination.data,
                "icd10": medical_history_form.icd10.data,
                "comment": medical_history_form.medical_comment.data,
            }
            values.update(anamnesis_values)
            new_medical_history = anamnesis.MedicalHistory(**values)
            meta.session.add(new_medical_history)
            meta.session.commit()

        elif anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_ADDICTION and addiction_form.validate():
            values = {
                "type": addiction_form.addiction_type.data,
                "comment": addiction_form.addiction_comment.data,
                "begin": addiction_form.begin_addiction.data,
                "end": addiction_form.end_addiction.data,
            }
            values.update(anamnesis_values)
            new_addiction = anamnesis.Addiction(**values)
            meta.session.add(new_addiction)
            meta.session.commit()

        elif anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_TREATMENT and treatment_form.validate():
            values = {
                "name": treatment_form.molecule.data,
                "posologia": treatment_form.posologia.data,
                "begin": treatment_form.begin_treatment.data,
                "end": treatment_form.end_treatment.data,
            }
            values.update(anamnesis_values)
            new_treatment = anamnesis.Treatment(**values)
            meta.session.add(new_treatment)
            meta.session.commit()

        elif anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_PAST_SURGERY and past_surgery_form.validate():
            values = {
                "surgery_type": past_surgery_form.surgery_type.data,
                "problem": past_surgery_form.problem.data,
                "complication": past_surgery_form.complication.data,
            }
            values.update(anamnesis_values)
            new_past_surgery = anamnesis.PastSurgery(**values)
            meta.session.add(new_past_surgery)
            meta.session.commit()

        elif anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_ALLERGY and allergy_form.validate():
            values = {
                "type": allergy_form.allergy_type.data,
                "allergen": allergy_form.allergen.data,
                "reaction": allergy_form.reaction.data,
            }
            values.update(anamnesis_values)
            new_allergy = anamnesis.Allergy(**values)
            meta.session.add(new_allergy)
            meta.session.commit()

        elif anamnesis_form.anamnesis_type.data == constants.ANAMNESIS_ORAL_HYGIENE and oral_hygiene_form.validate():
            values = {
                "type": oral_hygiene_form.oral_type.data,
                "frequency": oral_hygiene_form.frequency.data,
                "comment": oral_hygiene_form.oral_comment.data,
            }
            values.update(anamnesis_values)
            new_oral_hygiene = anamnesis.OralHygiene(**values)
            meta.session.add(new_oral_hygiene)
            meta.session.commit()

        else:
            if survey_entry:
                survey_entry -= 1
            clear_form = False
            render_template(
                "add_anamnesis_entry.html",
                patient=patient,
                appointment=appointment,
                question=question,
                survey_id=survey_id,
                survey_entry=survey_entry,
                anamnesis_form=anamnesis_form,
                medical_history_form=medical_history_form,
                addiction_form=addiction_form,
                treatment_form=treatment_form,
                past_surgery_form=past_surgery_form,
                allergy_form=allergy_form,
                oral_hygiene_form=oral_hygiene_form,
                constants=constants,
                clear_form=clear_form,
            )

        return redirect(
            url_for(
                "add_anamnesis_entry",
                patient_id=patient_id,
                appointment_id=appointment_id,
                survey_id=survey_id,
                survey_entry=survey_entry,
            )
        )
    clear_form = True

    return render_template(
        "add_anamnesis_entry.html",
        patient=patient,
        appointment=appointment,
        question=question,
        survey_id=survey_id,
        survey_entry=survey_entry,
        anamnesis_form=anamnesis_form,
        medical_history_form=medical_history_form,
        addiction_form=addiction_form,
        treatment_form=treatment_form,
        past_surgery_form=past_surgery_form,
        allergy_form=allergy_form,
        oral_hygiene_form=oral_hygiene_form,
        constants=constants,
        clear_form=clear_form,
    )