Ejemplo n.º 1
0
        public Model.OnkologyTreat GetOnkologyTreat(Model.Recourse rec, Model.Event evt)
        {
            string id = string.Format("{0,6}", evt.Identity);

            selectOnkologyTreat.Parameters[0].Value = id;

            Model.OnkologyTreat result = null;

            ExecuteReader(selectOnkologyTreat, r => {
                string mes1 = aStrings.Read(r, 0);
                result      = new Model.OnkologyTreat(mes1);
            });

            if (result != null)
            {
                var drugService = evt.Services.FirstOrDefault(s => s.ServiceCode / 10000 == 52);
                if (drugService != null)
                {
                    var oncoService = Lib.OncoTherapyHelper.Service[drugService.ServiceCode];
                    if (oncoService != null)
                    {
                        result.Services   = new invox.Model.OncologyService[] { oncoService };
                        evt.ClinicalGroup = Lib.OncoTherapyHelper.Service.ClinicalCroupForService(drugService.ServiceCode);
                        oncoService.Drugs.First().Date = drugService.DateTill;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 2
0
        public DataContract.PurchaseTicketResponse PurchaseTicket(DataContract.PurchaseTicketRequest request)
        {
            DataContract.PurchaseTicketResponse response = new DataContract.PurchaseTicketResponse();
            try
            {
                if (_purchaseHistory.IsUniqueResponse(request.CorrelationId))
                {
                    Model.Event ticketEvent = this._repository.FindBy(new Guid(request.EventId));
                    var         reservation = ticketEvent.GetReservationWith(new Guid(request.ReservationId));
                    if (ticketEvent.CanPurchaseTicketWith(reservation.Id))
                    {
                        var purchase = ticketEvent.PurchaseTicketWith(reservation.Id);
                        this._repository.Save(ticketEvent);
                        response         = purchase.ConvertToTicketPurchaseResponse();
                        response.Success = true;
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "can no longer purchase with this reservation";
                    }
                }
                else
                {
                    response = _purchaseHistory.RetrievePreviousResponseFor(request.CorrelationId);
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ErrorLog.GenerateErrorRef(ex);
            }

            return(response);
        }
Ejemplo n.º 3
0
        public async Task <ActionResult <Model.Event> > Update(int id, Model.Event userEvent)
        {
            userEvent.Id = id;

            try
            {
                var input = _mapper.Map <AuthoAPI.Models.Event>(userEvent);
                _context.Entry(input).State = EntityState.Modified;

                var result = await _context.Event.FindAsync(id);

                await _context.SaveChangesAsync();

                return(_mapper.Map <Model.Event>(result));
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EventExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 4
0
 public void Add(Model.Event E)
 {
     /* Solution 1:
      * Find if the event is in the DB;
      *
      * var query = from Event in _dbContext.Events
      * where Event.Date == E.Date and Event.Name == E.Name
      * select Event;
      *
      * if (query.ToList().Count > 0) {
      *  throw new ArgumentException();
      * }
      *
      * Solution 2:
      *
      * Migration on the table, adding another field. Like, a hash (Name+Date).
      *
      * var gimme_hash = Sha1.Create(E.Name+E.Date);
      * gimme_hash.Hash;
      * _dbContext.Event.Find(e => e.Hash == E.hash);
      * _dbContext.Event.SingleOrDefault(e => e.Hash == E.hash);
      * OR use LINQ
      *
      * if (query.ToList().Count > 0) {
      *  throw new ArgumentException();
      * }
      *
      * Thinking forward, we want the UI window handling the Event addition to tell the user they
      * can't add duplicates
      * */
     _dbContext.Events.Add(E);
     _dbContext.SaveChanges();
 }
Ejemplo n.º 5
0
 public DataContract.ReserveTicketResponse ReserveTicket(DataContract.ReserveTicketRequest request)
 {
     DataContract.ReserveTicketResponse response = new DataContract.ReserveTicketResponse();
     try
     {
         Model.Event             ticketEvent = this._repository.FindBy(new Guid(request.EventId));
         Model.TicketReservation reservation;
         if (ticketEvent.CanReserveTicket(request.TicketQty))
         {
             reservation = ticketEvent.ReserveTicket(request.TicketQty);
             this._repository.Save(ticketEvent);
             response         = reservation.ConvertToTicketReservationResponse();
             response.Success = true;
         }
         else
         {
             response.Success = false;
             response.Message = string.Format("There're only {0} tickets available.", ticketEvent.AvailableAllocation());
         }
     }
     catch (Exception ex)
     {
         response.Success = false;
         response.Message = ErrorLog.GenerateErrorRef(ex);
     }
     return(response);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Создать событие и заполнить его доступными полями
        /// </summary>
        public Model.Event ToEvent(Model.Recourse rec, Model.OrderSection section)
        {
            Model.Event result = new Model.Event();

            // result.Services;                         - Pool.LoadEvents
            result.Identity = ServiceId;
            result.Unit     = Unit;

            if (rec.IsHospitalization)
            {
                result.BedProfile = BedProfile;
                result.Transfer   = Model.Transfer.Independently;
            }
            else
            {
                result.Transfer = Model.Transfer.None;
            }

            result.Child  = Child;
            result.Reason = AidConditions == "3" ? InternalReasonHelper.ToVisitAim(InternalReason) : string.Empty;

#if FOMS
            result.LocalReason = InternalReason.ToFomsReason(soul);
#endif

            result.CardNumber = CardNumber;
            //result.Transfer;                          - Pool.LoadEvents
            //result.DateFrom;                          - Pool.LoadEvents
            result.DateTill = Date;
            //result.BedDays;                           - Pool.LoadEvents
            //result.PrimaryDiagnosis;                  - Pool.LoadEvents

            result.MainDiagnosis = MainDiagnosis;

            //result.FirstIdentified;                   - Pool.LoadEvents
            //result.ConcurrentDiagnosis;               - Pool.LoadEvents
            //result.ComplicationDiagnosis;             - Pool.LoadEvents
            //result.DispensarySupervision;             - Pool.LoadEvents
            //result.ConcurrentMesCode;                 - Pool.LoadEvents

            // Hack to avoid oncology treatment services in polyclinic
            //result.Rehabilitation = Rehabilitation || (section == Model.OrderSection.D4 && !rec.SuspectOncology);
            result.Rehabilitation = Rehabilitation && !rec.SuspectOncology;

            result.Quantity       = Quantity;
            result.SpecialityCode = SpecialityCode;
            result.DoctorCode     = DoctorCode;

            //result.Tariff;                            - Pool.LoadEvents
            //result.Total;                             - Pool.LoadEvents

            // TODO: RecourseAux - HiTech data
            //result.HiTechKind;
            //result.HiTechMethod;
            //result.HiTechCheckDate;
            //result.HiTechCheckNumber;
            //result.HiTechPlannedHospitalizationDate;

            return(result);
        }
Ejemplo n.º 7
0
 public void Save(Model.Event eventEntity)
 {
     if (events.Exists(x => x.Id == eventEntity.Id))
     {
         events.RemoveAt(events.FindIndex(x => x.Id == eventEntity.Id));
     }
     events.Add(eventEntity);
 }
Ejemplo n.º 8
0
        public async Task <string> InsertEvent(Model.Event _Event)
        {
            string Status = string.Empty;
            var    Event  = Mapper.Map <Model.Event, Data.Event>(_Event);
            var    result = data.Post(Event);

            Status = result ? "Event created successfully." : "Failed to submit Event";
            return(Status);
        }
Ejemplo n.º 9
0
        public async Task <string> UpdateEvent(int Id, Model.Event _Event)
        {
            string Status = string.Empty;
            var    Event  = Mapper.Map <Model.Event, Data.Event>(_Event);
            var    result = data.Put(Id, Event);

            Status = result ? "Event updated successfully." : "Failed to update Event";
            return(Status);
        }
        public FinishedEventsControl(Model.Event eventToRender, Model.User userLoggedIn)
		{
			this.InitializeComponent();

            _userLoggedIn = userLoggedIn;
            _eventToRender = eventToRender;
            _schedulerEvent = new WpfScheduler.Event() { EventInfo = _eventToRender };

            LoadEventInfo();
		}
Ejemplo n.º 11
0
 public EventRepository()
 {
     if (events == null)
     {
         events = new List <Model.Event>();
         Model.Event ev = new Model.Event("sports game", 100);
         ev.Id = new Guid("2de874d0-00b7-4c86-9925-c7f2c243151c");
         events.Add(ev);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Загрузить сопутствующие заболевания для события
        /// </summary>
        /// <param name="evt">Событие, которому требуется установить сопутствующие заболевания</param>
        /// <param name="services">Услуги, оказанные в рамках события. Сопутствующие берутся из них</param>
        public void FindConcurrentDiagnoses(Model.Event evt, List <ServiceAux> services, Model.OrderSection section)
        {
            var d1 = services.Select(s => s.ConcurrentDiagnosis)
                     .Where(d => !string.IsNullOrEmpty(d) && d != evt.MainDiagnosis)
                     .Distinct();

            if (d1.Count() > 0)
            {
                evt.ConcurrentDiagnoses = d1.ToList();
            }
            else
            {
                evt.ConcurrentDiagnoses = null;
            }

            // Проверить соответствие диагноза цели обращения (только для разделов D1 и D4)
            if (section == Model.OrderSection.D1 || section == Model.OrderSection.D4)
            {
                DiagnosisKind kind = InternalReason.GetDiagnosisKind();

                if (!kind.Matches(MainDiagnosis))
                {
                    // Если не соответствует

                    // Переносим основное заболевание в сопутствующие
                    if (evt.ConcurrentDiagnoses == null)
                    {
                        evt.ConcurrentDiagnoses = new List <string>();
                    }
                    evt.ConcurrentDiagnoses.Add(MainDiagnosis);

                    // Попытаться найти подходящий в услугах...
                    d1 = services.Select(s => s.PrimaryDiagnosis).Where(d => kind.Matches(d));
                    if (d1.Count() > 0)
                    {
                        evt.MainDiagnosis = MainDiagnosis = d1.First();
                    }
                    else
                    {
                        // ...либо поставить диагноз по умолчанию
                        if (kind == DiagnosisKind.Treatment)
                        {
                            Lib.Logger.Log(string.Format("Не найден подходящий диагноз для случая лечебной цели: RECID {0} (диагноз {1})",
                                                         evt.CardNumber,
                                                         MainDiagnosis));
                        }
                        evt.MainDiagnosis = MainDiagnosis = InternalReason.DefaultDiagnosis();
                        evt.Services.ForEach(s => s.Diagnosis = MainDiagnosis);
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private async void frmAuth_Load(object sender, EventArgs e)
        {
            if (this.eventId != null)
            {
                this.Event = await apiService_Event.GetById <Model.Event>(eventId);

                lblEvent.Text = Event.EventName;
            }
            else
            {
                lblEvent.Text = "None";
            }
        }
 public TestLogicPerferomance(string filepath, string filePathToMove)
 {
     FilePath        = filepath;
     FilePathToMove  = filePathToMove;
     sportToAdd      = new Model.Sport();
     categoryToAdd   = new Model.Category();
     tournamentToAdd = new Model.Tournament();
     matchEventToAdd = new Model.Event();
     competitorToAdd = new Model.Competitor();
     betType         = new Model.BetType();
     marketsToAdd    = new Model.Markets();
     fileHelper      = new FileSearchHelper(FilePath);
     serializer      = new XmlSerializer(typeof(BetradarBetData));
 }
Ejemplo n.º 15
0
 public static EventVM Map(Model.Event Event)
 {
     return(new EventVM()
     {
         Id = Event.Id,
         Name = Event.Name,
         Description = Event.Description,
         StartDate = Event.StartDate,
         EndDate = Event.EndDate,
         Longitude = Event.Longitude,
         Latitude = Event.Latitude,
         Radius = Event.Radius
     });
 }
Ejemplo n.º 16
0
        public void CreateEvent()
        {
            Model.Event tempEvent = new Model.Event();

            tempEvent.Id          = evm.Id;
            tempEvent.Name        = evm.Name;
            tempEvent.Description = evm.Description;
            tempEvent.Place       = evm.Place;
            tempEvent.DateTime    = Converter.DateTimeConverter.DateTimeOffsetAndTimeSetToDateTime(evm.Date, evm.Time);

            Model.EventCatalogSingleton.Instance.EventListe.Add(tempEvent);

            // Model.EventCatalogSingleton.Instance.EventListe.Add(new Model.Event() { });
        }
Ejemplo n.º 17
0
        public static DTO.Event TranslateModelEventToDTOEvent(Model.Event e)
        {
            if (e == null)
            {
                return(null);
            }

            return(new DTO.Event
            {
                Id = e.Id,
                Name = e.Name,
                InstigatorUser = UserMapper.TranslateModelUserToDTOUser(e.InstigatorUser),
                Timestamp = e.Timestamp
            });
        }
Ejemplo n.º 18
0
        private void Event_GetAll()
        {
            DataTable dtEvent;

            Model.Event evnt = new Model.Event()
            {
            };
            using (var scope = Startup.Container.BeginLifetimeScope())
            {
                var Event = scope.Resolve <IEvent>();
                dtEvent = Event.Event_GetAll(evnt);
            }

            dgvEvent.DataSource = dtEvent;
            dgvEvent.DataBind();
        }
Ejemplo n.º 19
0
 public void DeleteEvent(Model.Event eventToDelete)
 {
     try
     {
         using (var db = new GuestAppContext())
         {
             var eventToRemove = db.Events.Find(eventToDelete.Id);
             db.Events.Remove(eventToRemove);
             db.SaveChanges();
         }
     }
     catch (Exception e)
     {
         throw;
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Получить услуги для события
        /// </summary>
        IEnumerable <ServiceAux> LoadServices(RecourseAux ra, Model.Event evt)
        {
            DbCommand command = null;

            switch (ra.InternalReason)
            {
            case InternalReason.AmbTreatment:
            case InternalReason.DayHosp:
            case InternalReason.SurgeryDayHosp:
                command = selectServicesTreatment;
                break;

            case InternalReason.Stage1:
                command = selectServicesStage1;
                break;

            case InternalReason.Stage2:
                command = selectServicesStage2;
                break;

            case InternalReason.Prof:
                command = selectServicesProf;
                break;

            case InternalReason.Other:
            case InternalReason.BriefTreatment:
            case InternalReason.DispRegister:
            case InternalReason.Emergency:
            case InternalReason.Diagnostics:
                command = selectServicesByDate;
                string d = ra.Date.ToString("MM/dd/yyyy").Replace('.', '/');
                command.Parameters[3].Value = d;
                break;
            }

            if (command != null)
            {
                command.Parameters[0].Value = string.Format("{0,6}", ra.PersonId);
                command.Parameters[1].Value = ra.Department;
                command.Parameters[2].Value = ra.InitialDiagnosis;
                return(aService.Load(command));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 21
0
        private async void frmPresenceFinal_Load(object sender, EventArgs e)
        {
            this.Enabled = false;

            //filling comboboxes with data
            loadComboBoxes.loadGroups(cbGroup);
            loadComboBoxes.loadRoles(cbRole);
            userEvent = await apiService_event.GetById<Model.Event>(eventId);
            if (this.userEvent == null)
            {
                //MessageBox to explain
                this.Close();
            }
            //filling data grid view with data based on filter data
            loadData();
            setup = false;
            this.Enabled = true;
        }
        private DataTable LoadEventData()
        {
            DataTable dtEvent;

            Model.Event even = new Model.Event()
            {
                EventName      = txtEventName.Text.Trim(),
                BranchId       = Convert.ToInt32(ddlBranch.SelectedValue),
                EventTypeId    = Convert.ToInt32(ddlEventType.SelectedValue),
                EventStartDate = (string.IsNullOrEmpty(txtEventStartDate.Text) ? DateTime.MinValue : Convert.ToDateTime(txtEventStartDate.Text)),
                EventEndDate   = (string.IsNullOrEmpty(txtEventEndDate.Text) ? DateTime.MinValue : Convert.ToDateTime(txtEventEndDate.Text)),
            };
            using (var scope = Startup.Container.BeginLifetimeScope())
            {
                var Event = scope.Resolve <IEvent>();
                dtEvent = Event.Event_GetAll(even);
            }
            return(dtEvent);
        }
        private void LoadEvents()
        {
            DataTable dtEvent;

            Model.Event evnt = new Model.Event()
            {
            };
            using (var scope = Startup.Container.BeginLifetimeScope())
            {
                var Event = scope.Resolve <IEvent>();
                dtEvent = Event.Event_GetAll(evnt);
            }
            if (dtEvent != null)
            {
                ddlEvent.DataSource     = dtEvent;
                ddlEvent.DataTextField  = "EventName";
                ddlEvent.DataValueField = "EventId";
                ddlEvent.DataBind();
            }
            ddlEvent.InsertSelect();
        }
Ejemplo n.º 24
0
 protected void btnSave_Click(object sender, EventArgs e)
 {
     try
     {
         Model.Event evnt = new Model.Event()
         {
             EventId        = this.EventId,
             EventName      = txtEventName.Text.Trim(),
             EventTypeId    = int.Parse(ddlEventType.SelectedValue),
             BranchId       = int.Parse(ddlBranch.SelectedValue),
             CreatedBy      = int.Parse(HttpContext.Current.User.Identity.Name),
             EventStartDate = (string.IsNullOrEmpty(txtEventStartDate.Text.Trim())) ? DateTime.MinValue : Convert.ToDateTime(txtEventStartDate.Text),
             EventEndDate   = (string.IsNullOrEmpty(txtEventEndDate.Text.Trim())) ? DateTime.MinValue : Convert.ToDateTime(txtEventEndDate.Text),
             Description    = txtDescription.Text.Trim(),
             Venue          = txtVenue.Text.Trim(),
         };
         using (var scope = Startup.Container.BeginLifetimeScope())
         {
             var Event = scope.Resolve <IEvent>();
             EventId = Event.Event_Save(evnt);
         }
         if (EventId > 0)
         {
             ClearEventControls();
             Event_GetAll();
             Message.IsSuccess = true;
             Message.Text      = "Saved Successfully";
         }
         else
         {
             Message.IsSuccess = false;
             Message.Text      = "Not saved.";
         }
     }
     catch (Exception ex)
     {
         Message.IsSuccess = false;
         Message.Text      = ex.Message;
     }
 }
Ejemplo n.º 25
0
        public async Task <ActionResult <Model.Event> > Insert(Model.Event userEvent)
        {
            var newEvent = _mapper.Map <AuthoAPI.Models.Event>(userEvent);

            _context.Event.Add(newEvent);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (EventExists(userEvent.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            //return CreatedAtAction("Get", new { id = newEvent.Id }, newEvent);
            return(_mapper.Map <Model.Event>(newEvent));
        }
Ejemplo n.º 26
0
        private void Event_GetById()
        {
            DataTable dtEvent;

            Model.Event evnt = new Model.Event()
            {
                EventId = this.EventId
            };
            using (var scope = Startup.Container.BeginLifetimeScope())
            {
                var Event = scope.Resolve <IEvent>();
                dtEvent = Event.Event_GetAll(evnt);
            }
            if (dtEvent != null && dtEvent.Rows.Count > 0)
            {
                txtEventName.Text          = dtEvent.Rows[0]["EventName"].ToString();
                txtDescription.Text        = dtEvent.Rows[0]["Description"].ToString();
                txtEventStartDate.Text     = (dtEvent.Rows[0]["EventStartDate"] == DBNull.Value) ? "" : Convert.ToDateTime(dtEvent.Rows[0]["EventStartDate"].ToString()).ToString("dd MMM yyyy");
                txtEventEndDate.Text       = (dtEvent.Rows[0]["EventEndDate"] == DBNull.Value) ? "" : Convert.ToDateTime(dtEvent.Rows[0]["EventEndDate"].ToString()).ToString("dd MMM yyyy");
                txtVenue.Text              = dtEvent.Rows[0]["Venue"].ToString();
                ddlBranch.SelectedValue    = (dtEvent.Rows[0]["BranchId"] == DBNull.Value) ? "0" : dtEvent.Rows[0]["BranchId"].ToString();
                ddlEventType.SelectedValue = dtEvent.Rows[0]["EventTypeId"].ToString();
            }
        }
        private void AddEvent(System.DateTime eventToAdd)
        {
            Model.Event ev = new Model.Event()
            {
                StartEvent = eventToAdd,
                EndEvent = eventToAdd.AddMinutes(1.0)
            };

            Model.Event overlappedEvent = OverlappedWithExistingEvent(ev, scheduler.Events.ToList());
            if (overlappedEvent != null)
            {
                MessageBox.Show(string.Format("No se puede agendar una cita a las {0} hrs."
                                    +"\nExiste una cita para el tratamiento de '{1}' que inicia a las {2} hrs"
                                    + " y termina a las {3} hrs.",
                                    eventToAdd.ToString("HH:mm"),
                                    overlappedEvent.Treatment.Name,
                                    overlappedEvent.StartEvent.ToString("HH:mm"),
                                    overlappedEvent.EndEvent.ToString("HH:mm")), 
                                "Advertencia", 
                                MessageBoxButton.OK,
                                MessageBoxImage.Information);
                return;
            }
                
            new AddEventModal(scheduler, eventToAdd, _userLoggedIn).ShowDialog();   
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values.Length == 5)
            {
                Model.Event modelEvent = new Model.Event()
                {
                    IsException = (bool)values[0],
                    IsCanceled = (bool)values[1],
                    IsCompleted = (bool)values[2],
                    PatientSkips = (bool)values[3],
                    IsConfirmed = (bool)values[4]
                };

                WpfScheduler.Event scheduleEvent = new WpfScheduler.Event() { EventInfo = modelEvent };

                return scheduleEvent.EventStatusString;
            }
            else if (values.Length == 1 && values[0] is DateTime)
            {
                DateTime dateToShow = (DateTime)values[0];
                return dateToShow.ToString("dd/MMMM/yyyy") + dateToShow.ToString(", HH:mm") + " hrs";
            }

            return string.Empty;
        }
        private void btnAccept_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (cbPatientName.SelectedIndex == -1)
            {
                MessageBox.Show("Seleccione un paciente", "Informaicón", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (cbTratmentName.SelectedIndex == -1)
            {
                MessageBox.Show("Seleccione un tratamiento", "Informaicón", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            List<Model.Event> skippedEvents = _selectedPatient.Events
                                                .Where(ev => ev.IsCompleted && ev.PatientSkips)
                                                .OrderBy(ev => ev.StartEvent)
                                                .ToList();

            
            if (skippedEvents.Count >= maxSkippedEvents)
            {
                string skippedEventsMessage = string.Empty;
                for (int i = 0; i < skippedEvents.Count; i++)
                {
                    skippedEventsMessage += string.Format(
                                                "\nFalta #{0}:" +
                                                "\n -Tratamiento: {1}" +
                                                "\n -Día de la cita: {2}" +
                                                "\n -Hora de inicio de la cita: {3}" +
                                                "\n -Hora de fin de la cita: {4}",
                                                i + 1,
                                                skippedEvents[i].Treatment.Name,
                                                skippedEvents[i].StartEvent.ToString("D"),
                                                skippedEvents[i].StartEvent.ToString("HH:mm") + " hrs",
                                                skippedEvents[i].EndEvent.ToString("HH:mm") + " hrs" + (i == skippedEvents.Count - 1 ? "" : "\n"));
                }

                MessageBox.Show(string.Format("El paciente seleccionado no puede agendar cita, ya que cuenta con {0} {1} y el máximo permitido es de {2} {3}\n{4}",
                                                    skippedEvents.Count,
                                                    skippedEvents.Count == 1 ? "falta" : "faltas",
                                                    maxSkippedEvents,
                                                    maxSkippedEvents == 1 ? "falta" : "faltas",
                                                    skippedEventsMessage
                                                ),
                                                "Advertencia",
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Warning);
                return;
            }

            //Health Insurance
            if (_selectedPatient.HasHealthInsurance)
            {
                if (_selectedPatient.IsDentegra)
                {
                    List<Model.DentegraAuthorization> elegibilities = _selectedPatient.DentegraAuthorizations
                                                                       .OrderByDescending(a => a.AuthorizationDate)
                                                                       .Take(1)
                                                                       .ToList();

                    if (elegibilities.Count == 0 || IsValidElegibility(elegibilities[0]) == false)
                    {
                        if (MessageBox.Show("El paciente seleccionado tiene seguro médico pero no cuenta con un número de " +
                                        "elegibilidad vigente.\n¿Desea agendar la cita?",
                                        "Advertencia",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Warning
                                    ) == MessageBoxResult.No || MainWindow.IsValidAdminPassword(_userLoggedIn) == false)
                        {
                            return;
                        }
                    }
                }
                else if (_selectedPatient.IsDiverse == false)
	            {
                    List<Model.Authorization> authorizations = _selectedPatient.Authorizations
                                                                       .OrderByDescending(a => a.AuthorizationDate)
                                                                       .Take(1)
                                                                       .ToList();

                    if (authorizations.Count == 0 || IsValidAuthorization(authorizations[0]) == false)
                    {
                        if (MessageBox.Show("El paciente seleccionado tiene seguro médico pero no cuenta con un número de " +
                                        "autorización vigente.\n¿Desea agendar la cita?",
                                        "Advertencia",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Warning
                                    ) == MessageBoxResult.No || MainWindow.IsValidAdminPassword(_userLoggedIn) == false)
                        {
                            return;
                        }
                    }
	            }
            }

            //Statements
            Model.Statement currentStatement = _selectedPatient.Statements
                                                    .Where(s => s.IsPaid == false)
                                                    .FirstOrDefault();

            if (currentStatement != null && currentStatement.ExpirationDate < DateTime.Now.Date)
            {
                MessageBox.Show("Este paciente posee un estado de cuenta que ha expirado (Estado de cuenta número: " + currentStatement.StatementId + ")" +
                                "\nEs necesario que el paciente liquide el estado de cuenta para poder agendarle una cita.",
                                "Información", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }

            //Check for restricted hours if user has recurrent canceled events
            List<Model.Event> canceledEventsInARow = AgendaWindow.GetPatientCanceledEventsInARow(_selectedPatient.PatientId, 3);
            if (canceledEventsInARow != null && IsRestrictedHour(_eventStart))
            {
                string canceledEventsMessage = string.Empty;
                for (int i = 0; i < canceledEventsInARow.Count; i++)
                {
                    canceledEventsMessage += string.Format(
                                                "\nCita cancelada #{0}:" +
                                                "\n -Tratamiento: {1}" +
                                                "\n -Día de la cita: {2}" +
                                                "\n -Hora de inicio de la cita: {3}" +
                                                "\n -Hora de fin de la cita: {4}",
                                                i + 1,
                                                canceledEventsInARow[i].Treatment.Name,
                                                canceledEventsInARow[i].StartEvent.ToString("D"),
                                                canceledEventsInARow[i].StartEvent.ToString("HH:mm") + " hrs",
                                                canceledEventsInARow[i].EndEvent.ToString("HH:mm") + " hrs" + (i == canceledEventsInARow.Count - 1 ? "" : "\n"));
                }

                MessageBox.Show(string.Format("El paciente seleccionado no puede agendar cita en un horario fuera de " + 
                                                "13 hrs. a 15 hrs. y 19 hrs. en delante, dado que se le ha penalizado " +
                                                "por 3 citas canceladas consecutivamente.\n\nUltimas 3 citas canceladas:\n{0}",
                                                    canceledEventsMessage
                                                ),
                                                "Advertencia",
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Warning);

                return;
            }

            Model.Event eventToAdd = new Model.Event();
            if (IsValidEvent(eventToAdd))
            {
                if (IsValidTreatmentInstrumentRelation(eventToAdd) == false)
                {
                    return;
                }

                if (BusinessController.Instance.Add<Model.Event>(eventToAdd))
                {
                    WpfScheduler.Event eventToAddScheduler = new WpfScheduler.Event() { EventInfo = eventToAdd };
                    _scheduler.AddEvent(eventToAddScheduler);

                    //Change status
                    bool eventStatusChangeRegistered = Utils.AddEventStatusChanges(null, eventToAddScheduler.EventStatus.ToString(), eventToAdd.EventId, _userLoggedIn.UserId);
                    if (eventStatusChangeRegistered == false)
                    {
                        MessageBox.Show("No se pudo guardar el cambio registrado en el estado de la cita", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                    //Discount UsesLeft to the selected instrument
                    List<Model.Instrument> missingInstruments = new List<Model.Instrument>();
                    if (eventToAdd.Instruments.Count > 0)
                    {
                        bool discountError = false;
                        foreach (var instrument in eventToAdd.Instruments)
                        {
                            if (instrument.UsesLeft > 0)
                            {
                                instrument.UsesLeft--;
                                discountError &= !BusinessController.Instance.Update<Model.Instrument>(instrument);
                            }
                            else
                            {
                                missingInstruments.Add(instrument);
                            }
                        }
                        
                        if (discountError)
                        {
                            MessageBox.Show("No se pudo descontar la cantidad de usos a algún instrumento seleccionado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }

                    if (missingInstruments.Count > 0)
                    {
                        MessageBox.Show("La cita se ha agendado, pero debe tomar en cuenta que faltan los siguientes instrumentos:\n-" + string.Join("\n-", missingInstruments.Select(i => i.Name)), "Información", MessageBoxButton.OK, MessageBoxImage.Information);   
                    }

                    this.Close();
                }
                else
                {
                    MessageBox.Show("No pudo ser agendada la cita", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Ejemplo n.º 30
0
        public IEnumerable <Model.DispAssignment> GetDispanserisationAssignments(Model.Recourse rec, Model.Event evt)
        {
            string id = string.Format("{0,6}", evt.Identity);

            selectDispDirections.Parameters[0].Value = id;
            List <Model.DispAssignment> result = null;

            Action <System.Data.Common.DbDataReader> onRead = r => {
                string codes  = (string)r["KSG"];
                string values = (string)r["KSG2"];

                Model.NeoSuspectDirection susp = null;
                if (rec.SuspectOncology)
                {
                    // TODO: Target clinic and service code for direction if oncology suspected
                    susp = new Model.NeoSuspectDirection()
                    {
                        Suspected     = true,
                        DirectionDate = evt.DateTill,
                        TargetClinic  = "XE3",
                        ServiceCode   = "XE3"
                    };
                }

                result = Model.DispAssignment.Make(codes.Trim(), values.Trim(), susp).ToList();
            };

            ExecuteReader(selectDispDirections, onRead);
            return(result);
        }
Ejemplo n.º 31
0
 public IEnumerable <Model.ConcomitantDisease> GetConcomitantDiseases(Model.InvoiceRecord irec, Model.Event evt)
 {
     selectConcomDiseases.Parameters[0].Value = irec.Person.Policy;
     selectConcomDiseases.Parameters[1].Value = evt.Unit;
     selectConcomDiseases.Parameters[2].Value = evt.MainDiagnosis;
     return(aConcomitantDisease.Load(selectConcomDiseases));
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Загрузить события для законченного случая
        /// </summary>
        /// <remarks>
        /// В настоящий момент одному законченному случаю соответствует одно события (т.к. нет
        /// внутрибольничных переводов). Здесь также загружаются услуги для события и обновляются
        /// поля законченного случая данными, которые удалось получить на этом этапе.
        /// </remarks>
        List <Model.Event> LoadEvents(Model.Recourse rec, RecourseAux ra, Model.OrderSection section)
        {
            // Extract single event from the RecourseAux:
            List <Model.Event> result = new List <Model.Event>();

            Model.Event evt = ra.ToEvent(rec, section);
            result.Add(evt);

            // Load auxilliary service records and service models
            List <ServiceAux> ss = LoadServices(ra, evt).Distinct(new ServiceComparer()).OrderBy(s => s.Date).ToList();

            if (ra.InternalReason == InternalReason.SurgeryDayHosp &&
                ss.Count(s => s.ServiceCode == ra.ServiceCode) > 1)
            {
                // Fix for:
                // Два случая ЦАХ у одного пациента с одним и тем же диагнозом
                //  будут выгружены как два случая, но в каждом ВСЕ услуги из обеих госпитализаций

                // Get main service
                ServiceAux sa = ss.FirstOrDefault(s => s.Date == ra.Date && s.ServiceCode == ra.ServiceCode);

                if (sa != null)
                {
                    // Get hospitalization dates
                    DateTime till = sa.Date;
                    DateTime from = till.WorkingDaysBefore(sa.BedDays, true);

                    // Select only services with relevant dates
                    IEnumerable <ServiceAux> sas = ss.Where(s => s.Date <= till && s.Date >= from);
                    ra.UpdateMedicalAid(rec, sas.Last());
                    evt.Services = sas.Select(s => s.ToService(ra)).ToList();

                    // ...supposedly at least one services is selected: the main one
                }
                else
                {
                    ra.UpdateMedicalAid(rec, ss.Last());
                    evt.Services = ss.Select(s => s.ToService(ra)).ToList();
                }
            }
            else
            {
                ra.UpdateMedicalAid(rec, ss.Last());
                evt.Services = ss.Select(s => s.ToService(ra)).ToList();
            }

            // 20190902 - Блядский вид медицинского вмешательства
            if (ra.InternalReason == InternalReason.SurgeryDayHosp)
            {
                Model.Service service = evt.Services.FirstOrDefault(s => s.ServiceCode / 100000 == 3);
                if (service != null)
                {
                    string interventionKind = GetInterventionKind(service.ServiceCode);
                    if (!string.IsNullOrEmpty(interventionKind))
                    {
                        evt.Services.ForEach(s => s.InterventionKind = interventionKind);
                    }
                }
            }

            // Код врача и специальности должны соответствовать закрывающей записи,
            // приводим в соответствие из ra (где было изменено в UpdateMedicalAid())
            evt.SpecialityCode = ra.SpecialityCode;
            evt.DoctorCode     = ra.DoctorCode;

            if (rec.IsHospitalization)
            {
                // Update profile-shifting transfer and total of the bed days
                ServiceAux serv = ss.Where(s => s.Transfer == Model.Transfer.Transferred).FirstOrDefault();

                // Turn transfer to ProfileShift if there has been bed profile change:
                if (serv != null &&
                    ss.GroupBy(s => s.BedProfile).Count() > 1)
                {
                    serv.Transfer = Model.Transfer.ProfileShift;
                }
                evt.BedDays = ss.Select(s => s.BedDays).Sum();
            }

            // Event dates
            if (ra.InternalReason == InternalReason.Stage1 || ra.InternalReason == InternalReason.Prof)
            {
                evt.DateTill = evt.Services.Max(s => s.DateTill);

                // For DD1 - start of the recourse is an antropometry
                ServiceAux sa = ss.Where(s => s.IsAntropometry()).FirstOrDefault();
                if (sa != null)
                {
                    evt.DateFrom = sa.Date;
                }
                else
                {
                    evt.DateFrom = ss.Min(s => s.Date);
                }

#if FOMS1
            }
            else if (ra.InternalReason == InternalReason.Prof)
            {
                // Work around error "Код способа оплаты не соответствует периоду лечения;
                // Цель обращения не соответствует способу оплаты медицинской помощи"
                // Prof events within a single day are discarded with this error
                evt.DateFrom = ra.Date.ShiftDays(-1);

                if (evt.DateFrom == ra.Date)
                {
                    evt.DateTill = ra.Date.ShiftDays(1);
                    Model.Service s = evt.Services.First();
                    if (s != null)
                    {
                        s.DateFrom = evt.DateTill;
                        s.DateTill = evt.DateTill;
                    }
                }
                else
                {
                    evt.DateTill = ra.Date;
                }
#endif
            }
            else
            {
                // For other cases service with minimal date (mayhap hospitalization - reason why not ss.Min())
                // 2 этап - пустая выборка
                try {
                    evt.DateFrom = evt.Services.Min(s => s.DateFrom);
                } catch (Exception e) {
                    Logger.Log(e.Message + string.Format(" - повод {0}, услуга {1}, S.RECID {2}", ra.InternalReason, ra.ServiceCode, ra.ServiceId));
                }
                evt.DateTill = evt.Services.Max(s => s.DateTill);
            }

#if FOMS
            // Задолбал ФОМС с их дурацкими ошибками: дд раз в 2 года ставит "неправильные даты", если дата начала и окончания не совпадают
            // В подушевой услуге ставим даты начала и окончания как во всем закрытом случае

            // 20190417 Хрен там, теперь не только обрезанная ДД
            Model.Service ser = evt.Services.FirstOrDefault(s => s.ServiceCode / 10000 == 5);
            if (ser != null)
            {
                ser.DateFrom = evt.DateFrom;
                ser.DateTill = evt.DateTill;
            }
#endif

            // May change evt and ra's MainDiagnosis:
            ra.FindConcurrentDiagnoses(evt, ss, section);

            // Service diagnosis as recorse's in case of diagnostics
            if (ra.InternalReason == InternalReason.Diagnostics)
            {
                evt.Services.ForEach(s => s.Diagnosis = ra.MainDiagnosis);
            }

            evt.ComplicationDiagnoses = ServiceAux.GetComplicationDiagnoses(ss);

            // Statistic code
            if (!string.IsNullOrEmpty(ra.MainDiagnosis) && ra.MainDiagnosis.First() != 'Z')
            {
                StatisticCode[] sc = ss
                                     .Select(s => s.StatisticCode)
                                     .Where(s => s > StatisticCode.None && s < StatisticCode.Dispensary)
                                     .ToArray();

                if (sc != null && sc.Count() > 0)
                {
                    evt.StatisticsCode = (((int)sc.Max()) - 1).ToString();
                }
                else
                {
                    evt.StatisticsCode = Dict.StatisticsCode.Instance.Get(ra.MainDiagnosis);
                }
            }

            // Профиль МП случая - по профилю закрывающей записи
            rec.Profile = ss.OrderBy(s => s.Date).Last().AidProfile;

            // Other Event fields which can be taken from the services
            evt.Tariff = evt.Services.Sum(s => s.Tariff);
            evt.Total  = evt.Services.Sum(s => s.Total);

            evt.PrimaryDiagnosis = ss.Max(s => s.PrimaryDiagnosis);
            evt.FirstIdentified  = ss.Any(s => s.FirstIdentified);

            if (ra.InternalReason == InternalReason.DispRegister)
            {
                evt.DispensarySupervision = ss.Max(s => s.DispensarySupervision);
                if (evt.DispensarySupervision == Model.DispensarySupervision.None)
                {
                    evt.DispensarySupervision = Model.DispensarySupervision.Observed;
                }
            }
            else if (section == Model.OrderSection.D3)
            {
                // 20190430 - D3 section: disp supervision is explicit
                evt.DispensarySupervision = ss.Max(s => s.DispensarySupervision);
                // Диагнозы на R ФОМС считает подлежащими Д-учету
                if (evt.DispensarySupervision < Model.DispensarySupervision.Observed ||
                    evt.DispensarySupervision > Model.DispensarySupervision.NotSubject)
                {
                    if ("ZY".Contains(evt.MainDiagnosis.First()))
                    {
                        evt.DispensarySupervision = Model.DispensarySupervision.NotSubject;
                    }
                    else
                    {
                        if (evt.FirstIdentified)
                        {
                            evt.DispensarySupervision = Model.DispensarySupervision.Taken;
                        }
                        else
                        {
                            evt.DispensarySupervision = Model.DispensarySupervision.Observed;
                        }
                    }
                }
            }

            evt.ConcurrentMesCode = ss.Max(s => s.ConcurrentMesCode);

            var d2 = ss.Where(s => s.Transfer != Model.Transfer.None);
            if (d2 != null && d2.Count() > 0)
            {
                evt.Transfer = d2.Min(s => s.Transfer);
            }

            // Other Recourse fields -"-
            rec.UnitShift   = ss.Any(s => s.Transfer == Model.Transfer.ProfileShift);
            rec.BirthWeight = ss.Max(s => s.BirthWeight);

            rec.DateFrom = evt.DateFrom;
            rec.DateTill = evt.DateTill;
            rec.Total    = evt.Total;
            rec.BedDays  = evt.BedDays;

            if (RecourseAux.NeedsDirection(rec))
            {
                // Extract directed-from in case when it is needed
                rec.DirectedFrom = ss.Max(s => s.DirectedFrom);
                if (string.IsNullOrEmpty(rec.DirectedFrom))
                {
                    // TODO: LPU code from local to federal
                    rec.DirectedFrom = Options.LpuCode;
                }
                rec.DirectionDate = rec.DateFrom;
            }

            return(result);
        }
Ejemplo n.º 33
0
 public IEnumerable <Model.OncologyConsilium> LoadOncologyConsilium(Model.Recourse rec, Model.Event evt)
 {
     // У нас не проводятся консилиумы
     yield return(new Model.OncologyConsilium(Model.OncologyConsiliumReason.NotNeeded, DateTime.Today));
 }
Ejemplo n.º 34
0
        public IEnumerable <Model.OncologyDirection> LoadOncologyDirections(Model.Recourse rec, Model.Event evt)
        {
            string id = string.Format("{0,6}", evt.Identity);

            selectOnkologyDirections.Parameters[0].Value = id;
            return(aOncologyDirection.Load(selectOnkologyDirections));
        }