Example #1
0
 def _has_changes(lc, lc_info):
     if (lc.numberContract != lc_info.get('number_contract', '')
             or lc.dateContract != safe_date(lc_info.get('date_contract'))
             or lc.lastName != lc_info.get('last_name', '')
             or lc.firstName != lc_info.get('first_name', '')
             or lc.patrName != lc_info.get('patr_name', '')
             or lc.birthDate != safe_date(lc_info.get('birth_date', '')) or
             lc.documentType_id != safe_traverse(lc_info, 'doc_type', 'id')
             or lc.serialLeft != lc_info.get('serial_left', '')
             or lc.serialRight != lc_info.get('serial_right', '')
             or lc.number != lc_info.get('number', '')
             or lc.regAddress != lc_info.get('reg_address', '')
             or lc.org_id != safe_traverse(lc_info, 'payer_org', 'id')):
         return True
     return False
Example #2
0
def create_services(event_id, service_groups, contract_id):
    """
    Создание или обновление услуг (действий) и последующее сохранение в бд.
    """
    actions = []
    errors = []
    for sg in service_groups:
        for act_data in sg['actions']:
            action_id = act_data['action_id']
            action_type = ActionType.query.get(sg['at_id'])
            data = {
                'amount': act_data.get('amount', 1),
                'account': act_data.get('account', 0),
                'coordDate': safe_datetime(act_data.get('coord_date')),
                'coordPerson_id': safe_traverse(act_data, 'coord_person', 'id')
            }
            if sg['is_lab']:
                data['plannedEndDate'] = safe_datetime(
                    act_data['planned_end_date'])
            assigned = act_data['assigned'] if sg['is_lab'] else None

            try:
                if not action_id:
                    data['contract_id'] = contract_id
                    action = create_new_action(sg['at_id'],
                                               event_id,
                                               assigned=assigned,
                                               data=data)
                else:
                    if assigned:
                        data['properties_assigned'] = assigned
                    action = Action.query.get(action_id)
                    action = update_action(action, **data)
            except ActionException, e:
                db.session.rollback()
                err_msg = u'Ошибка сохранения услуги "%s": %s.' % (
                    action_type.name, e.message)
                logger.error(err_msg + u'для event_id=%s' % event_id,
                             exc_info=True)
                errors.append(err_msg)
            except Exception, e:
                db.session.rollback()
                err_msg = u'Ошибка сохранения услуги "%s"' % action_type.name
                logger.error(err_msg + u'для event_id=%s' % event_id,
                             exc_info=True)
                errors.append(err_msg)
            else:
                db.session.add(action)
                try:
                    db.session.commit()
                except Exception, e:
                    db.session.rollback()
                    err_msg = u'Ошибка сохранения услуги "%s"' % action_type.name
                    logger.error(err_msg + u'для event_id=%s' % event_id,
                                 exc_info=True)
                    errors.append(err_msg)
                else:
Example #3
0
def create_or_update_local_contract(event, lc_info):
    lc_id = lc_info.get('id')
    number_contract = lc_info.get('number_contract', '')
    date_contract = safe_date(lc_info.get('date_contract'))
    last_name = lc_info.get('last_name', '')
    first_name = lc_info.get('first_name', '')
    patr_name = lc_info.get('patr_name', '')
    birth_date = safe_date(lc_info.get('birth_date', ''))
    document_type_id = safe_traverse(lc_info, 'doc_type', 'id')
    serial_left = lc_info.get('serial_left', '')
    serial_right = lc_info.get('serial_right', '')
    doc_number = lc_info.get('number', '')
    reg_address = lc_info.get('reg_address', '')
    org_id = safe_traverse(lc_info, 'payer_org', 'id')
    if event.id:
        if not event.localContract_id:
            lc = get_local_contract_for_new_event(lc_info)
        else:
            if not lc_id or (lc_id and lc_info.get('shared_in_events') and
                             _check_shared_local_contract_changes(lc_info)):
                lc = create_new_local_contract(lc_info)
            else:
                lc = EventLocalContract.query.get(lc_id)
                lc.numberContract = number_contract
                lc.dateContract = date_contract
                lc.lastName = last_name
                lc.firstName = first_name
                lc.patrName = patr_name
                lc.birthDate = birth_date
                lc.documentType_id = document_type_id
                lc.serialLeft = serial_left
                lc.serialRight = serial_right
                lc.number = doc_number
                lc.regAddress = reg_address
                lc.org_id = org_id
    else:
        lc = get_local_contract_for_new_event(lc_info)
    return lc
Example #4
0
def api_action_post():
    action_desc = request.get_json()
    action_id = action_desc['id']
    data = {
        'begDate': safe_datetime(action_desc['beg_date']),
        'endDate': safe_datetime(action_desc['end_date']),
        'plannedEndDate': safe_datetime(action_desc['planned_end_date']),
        'directionDate': safe_datetime(action_desc['direction_date']),
        'isUrgent': action_desc['is_urgent'],
        'status': action_desc['status']['id'],
        'setPerson_id': safe_traverse(action_desc, 'set_person', 'id'),
        'person_id': safe_traverse(action_desc, 'person', 'id'),
        'note': action_desc['note'],
        'amount': action_desc['amount'],
        'account': action_desc['account'] or 0,
        'uet': action_desc['uet'],
        'payStatus': action_desc['pay_status'] or 0,
        'coordDate': safe_datetime(action_desc['coord_date']),
        'office': action_desc['office']
    }
    properties_desc = action_desc['properties']
    if action_id:
        data['properties'] = properties_desc
        action = Action.query.get(action_id)
        action = update_action(action, **data)
    else:
        at_id = action_desc['action_type']['id']
        event_id = action_desc['event_id']
        action = create_new_action(at_id,
                                   event_id,
                                   properties=properties_desc,
                                   data=data)

    db.session.add(action)
    db.session.commit()

    v = ActionVisualizer()
    return jsonify(v.make_action(action))
Example #5
0
def create_new_local_contract(lc_info):
    err_msg = u'Ошибка сохранения обращения'
    lcon = EventLocalContract()

    date = lc_info.get('date_contract')
    number = lc_info.get('number_contract')
    if Settings.getBool('Event.Payment.1CODVD'):
        lcon.dateContract = datetime.date.today()
        lcon.numberContract = ''
    else:
        if not date:
            raise EventSaveException(err_msg,
                                     u'Не указана дата заключения договора.')
        lcon.dateContract = date
        if number is None:
            raise EventSaveException(err_msg, u'Не указан номер договора.')
        lcon.numberContract = number

    lcon.coordAgent = lc_info.get('coord_agent', '')
    lcon.coordInspector = lc_info.get('coord_inspector', '')
    lcon.coordText = lc_info.get('coord_text', '')
    lcon.sumLimit = lc_info.get('sum_limit', 0.0)
    lcon.lastName = lc_info.get('last_name')
    lcon.firstName = lc_info.get('first_name')
    lcon.patrName = lc_info.get('patr_name')
    lcon.birthDate = safe_date(lc_info.get('birth_date'))

    doc_type_id = safe_traverse(lc_info, 'doc_type', 'id')
    lcon.documentType_id = doc_type_id
    lcon.documentType = rbDocumentType.query.get(
        doc_type_id) if doc_type_id else None
    lcon.serialLeft = lc_info.get('serial_left')
    lcon.serialRight = lc_info.get('serial_right')
    lcon.number = lc_info.get('number')
    lcon.regAddress = lc_info.get('reg_address')
    lcon.org_id = safe_traverse(lc_info, 'payer_org', 'id')
    return lcon
Example #6
0
def api_event_save():
    event_data = request.json['event']
    close_event = request.json['close_event']
    event_id = event_data.get('id')
    is_diagnostic = event_data['event_type']['request_type']['code'] == '4'
    if is_diagnostic:
        execPerson = None
    else:
        execPerson = Person.query.get(event_data['exec_person']['id'])
    err_msg = u'Ошибка сохранения данных обращения'
    create_mode = not event_id
    if event_id:
        event = Event.query.get(event_id)
        event.deleted = event_data['deleted']
        event.eventType = EventType.query.get(event_data['event_type']['id'])
        event.execPerson = execPerson
        event.setDate = safe_datetime(event_data['set_date'])
        event.contract_id = event_data['contract']['id']
        event.isPrimaryCode = event_data['is_primary']['id']
        event.order = event_data['order']['id']
        event.orgStructure_id = event_data['org_structure']['id']
        event.result_id = event_data['result']['id'] if event_data.get(
            'result') else None
        event.rbAcheResult_id = event_data['ache_result'][
            'id'] if event_data.get('ache_result') else None
        event.note = event_data['note']

        local_contract = safe_traverse(request.json, 'payment',
                                       'local_contract')
        if event.payer_required:
            if not local_contract:
                raise EventSaveException(
                    err_msg, u'Не заполнена информация о плательщике.')
            lcon = create_or_update_local_contract(event, local_contract)
            event.localContract = lcon
        db.session.add(event)
    else:
        event = Event()
        event.setPerson_id = current_user.get_id()
        event.eventType = EventType.query.get(event_data['event_type']['id'])
        event.client_id = event_data['client_id']
        event.execPerson = execPerson
        event.setDate = safe_datetime(event_data['set_date'])
        event.externalId = get_new_event_ext_id(event.eventType.id,
                                                event.client_id)
        event.contract_id = event_data['contract']['id']
        event.isPrimaryCode = event_data['is_primary']['id']
        event.order = event_data['order']['id']
        event.org_id = event_data['organisation']['id']
        event.orgStructure_id = event_data['org_structure']['id']
        event.payStatus = 0
        event.note = event_data['note']
        event.uuid = get_new_uuid()

        local_contract = safe_traverse(request.json, 'payment',
                                       'local_contract')
        if event.payer_required:
            if not local_contract:
                raise EventSaveException(
                    err_msg, u'Не заполнена информация о плательщике.')
            lcon = create_or_update_local_contract(event, local_contract)
            event.localContract = lcon
        db.session.add(event)

        if not is_diagnostic:
            visit = Visit.make_default(event)
            db.session.add(visit)
            executives = Event_Persons()
            executives.person = event.execPerson
            executives.event = event
            executives.begDate = event.setDate
            db.session.add(executives)

    if close_event:
        exec_date = event_data['exec_date']
        event.execDate = safe_datetime(
            exec_date) if exec_date else datetime.datetime.now()

    try:
        db.session.commit()
    except EventSaveException:
        raise
    except Exception, e:
        logger.error(e, exc_info=True)
        db.session.rollback()
        return jsonify(
            {
                'name': err_msg,
                'data': {
                    'err_msg': 'INTERNAL SERVER ERROR'
                }
            }, 500, 'save event data error')
Example #7
0
def api_diagnosis_save():
    current_datetime = datetime.datetime.now()
    data = request.json
    diagnosis_id = data.get('diagnosis_id')
    diagnostic_id = data.get('diagnostic_id')
    if diagnosis_id:
        diagnosis = Diagnosis.query.get(diagnosis_id)
    else:
        diagnosis = Diagnosis()
        diagnosis.createDatetime = current_datetime
    if diagnostic_id:
        diagnostic = Diagnostic.query.get(diagnostic_id)
    else:
        diagnostic = Diagnostic()
        diagnostic.createDatetime = current_datetime

    diagnosis.modifyDatetime = current_datetime
    diagnostic.modifyDatetime = current_datetime

    diagnosis.client_id = data['client_id']
    diagnosis.person_id = data['person']['id']
    diagnosis.diagnosisType_id = safe_traverse(data, 'diagnosis_type', 'id')
    diagnosis.character_id = safe_traverse(data, 'character', 'id')
    diagnosis.dispanser_id = safe_traverse(data, 'dispanser', 'id')
    diagnosis.traumaType_id = safe_traverse(data, 'trauma', 'id')
    diagnosis.MKB = safe_traverse(data, 'mkb', 'code') or ''
    diagnosis.MKBEx = safe_traverse(data, 'mkb_ex', 'code') or ''
    if not diagnosis.endDate:
        diagnosis.endDate = current_datetime
    db.session.add(diagnosis)

    diagnostic.event_id = data['event_id']
    diagnostic.diagnosis = diagnosis
    diagnostic.diagnosisType_id = safe_traverse(data, 'diagnosis_type', 'id')
    diagnostic.character_id = safe_traverse(data, 'character', 'id')
    diagnostic.stage_id = safe_traverse(data, 'stage', 'id')
    diagnostic.phase_id = safe_traverse(data, 'phase', 'id')
    diagnostic.dispanser_id = safe_traverse(data, 'dispanser', 'id')
    diagnostic.traumaType_id = safe_traverse(data, 'trauma', 'id')
    diagnostic.healthGroup_id = safe_traverse(data, 'health_group', 'id')
    diagnostic.result_id = safe_traverse(data, 'result', 'id')
    diagnostic.notes = data.get('notes', '')
    diagnostic.sanatorium = 0
    diagnostic.hospital = 0
    diagnostic.speciality_id = 1
    diagnostic.version = 0
    diagnostic.rbAcheResult_id = safe_traverse(data, 'ache_result', 'id')
    if not diagnostic.setDate:
        diagnostic.setDate = current_datetime
    db.session.add(diagnostic)

    db.session.commit()
    return jsonify(None)
Example #8
0
def api_schedule_description_post():
    # TODO: validations

    def make_default_ticket(schedule):
        ticket = ScheduleTicket()
        ticket.schedule = schedule
        return ticket

    def make_tickets(schedule, planned, extra, cito):
        # here cometh another math
        dt = (datetime.datetime.combine(schedule.date, schedule.endTime) -
              datetime.datetime.combine(schedule.date,
                                        schedule.begTime)) / planned
        it = schedule.begTimeAsDt
        attendanceType = rbAttendanceType.query.filter(
            rbAttendanceType.code == 'planned').first()
        for i in xrange(planned):
            ticket = make_default_ticket(schedule)
            begDateTime = datetime.datetime.combine(schedule.date, it.time())
            ticket.begTime = begDateTime.time()
            ticket.endTime = (begDateTime + dt).time()
            ticket.attendanceType = attendanceType
            it += dt
            db.session.add(ticket)

        if extra:
            attendanceType = rbAttendanceType.query.filter(
                rbAttendanceType.code == 'extra').first()
            for i in xrange(extra):
                ticket = make_default_ticket(schedule)
                ticket.attendanceType = attendanceType
                db.session.add(ticket)

        if cito:
            attendanceType = rbAttendanceType.query.filter(
                rbAttendanceType.code == 'CITO').first()
            for i in xrange(cito):
                ticket = make_default_ticket(schedule)
                ticket.attendanceType = attendanceType
                db.session.add(ticket)

    schedule_data = request.json
    schedule = schedule_data['schedule']
    quotas = schedule_data['quotas']
    person_id = schedule_data['person_id']
    dates = [day['date'] for day in schedule]

    if schedule:
        ok, msg = delete_schedules(dates, person_id)
        if not ok:
            return jsonify({}, 422, msg)

    for day_desc in schedule:
        date = safe_date(day_desc['date'])
        roa = day_desc['roa']

        if roa:
            new_sched = Schedule()
            new_sched.person_id = person_id
            new_sched.date = date
            new_sched.reasonOfAbsence = rbReasonOfAbsence.query.\
                filter(rbReasonOfAbsence.code == roa['code']).first()
            new_sched.begTime = '00:00'
            new_sched.endTime = '00:00'
            new_sched.numTickets = 0
            db.session.add(new_sched)
        else:
            new_scheds_by_rt = defaultdict(list)
            for sub_sched in day_desc['scheds']:
                new_sched = Schedule()
                new_sched.person_id = person_id
                new_sched.date = date
                new_sched.begTimeAsDt = safe_time_as_dt(sub_sched['begTime'])
                new_sched.begTime = new_sched.begTimeAsDt.time()
                new_sched.endTimeAsDt = safe_time_as_dt(sub_sched['endTime'])
                new_sched.endTime = new_sched.endTimeAsDt.time()
                new_sched.receptionType_id = safe_traverse(
                    sub_sched, 'reception_type', 'id')
                office_id = safe_traverse(sub_sched, 'office', 'id')
                if not office_id and safe_traverse(sub_sched, 'reception_type',
                                                   'code') == 'amb':
                    return jsonify({}, 422, u'На %s не указан кабинет' %
                                   format_date(date))
                new_sched.office_id = office_id
                new_sched.numTickets = sub_sched.get('planned', 0)

                planned_count = sub_sched.get('planned')
                if not planned_count:
                    return jsonify(
                        {}, 422, u'На %s указаны интервалы с нулевым планом' %
                        format_date(date))
                make_tickets(new_sched,
                             planned_count, sub_sched.get('extra', 0),
                             sub_sched.get('CITO', 0))

    for quota_desc in quotas:
        date = safe_date(quota_desc['date'])
        QuotingByTime.query.filter(
            QuotingByTime.doctor_id == person_id,
            QuotingByTime.quoting_date == date).delete()
        new_quotas = quota_desc['day_quotas']
        for quota in new_quotas:
            quota_record = QuotingByTime()
            quota_record.quoting_date = date
            quota_record.doctor_id = person_id
            quota_record.QuotingTimeStart = safe_time_as_dt(
                quota['time_start'])
            quota_record.QuotingTimeEnd = safe_time_as_dt(quota['time_end'])
            quota_record.quotingType_id = quota['quoting_type']['id']
            db.session.add(quota_record)

    db.session.commit()

    start_date_s = schedule_data.get('start_date')
    start_date = datetime.datetime.strptime(start_date_s, '%Y-%m').date()
    end_date = start_date + datetime.timedelta(
        calendar.monthrange(start_date.year, start_date.month)[1])
    context = ScheduleVisualizer()
    person = Person.query.get(person_id)
    return jsonify(
        context.make_person_schedule_description(person, start_date, end_date))