Exemplo n.º 1
0
        void SyncEntities <T>(List <T> items) where T : RealmObject, ISync
        {
            var    client     = new RestClient(HOST_URL);
            string entityPath = typeof(T).Name;

            using (var trans = MainDatabase.BeginTransaction()) {
                foreach (var item in items)
                {
                    var request = new RestRequest(entityPath, Method.POST);
                    request.AddQueryParameter(@"access_token", ACCESS_TOKEN);
                    request.JsonSerializer = new NewtonsoftJsonSerializer();
                    request.AddJsonBody(item);
                    var response = client.Execute(request);
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Created:
                        item.IsSynced = true;
                        break;
                    }
                    SDiag.Debug.WriteLine(response.StatusDescription);
                }
                trans.Commit();
            }
        }
Exemplo n.º 2
0
        void RowDelete_Click(object sender, EventArgs e)
        {
            var adapter = (RoutePharmacyAdapter)PharmacyTable.Adapter;

            var rowForDelete = (LinearLayout)((ImageView)sender).Parent;

            var routeItemUUID = (string)rowForDelete.GetTag(Resource.String.RouteItemUUID);

            MainDatabase.DeleteEntity <RouteItem>(routeItemUUID);

            int pos   = (int)rowForDelete.GetTag(Resource.String.Position);
            int index = (int)rowForDelete.GetTag(Resource.String.RouteItemOrder);

            RouteTable.RemoveView(rowForDelete);

            using (var trans = MainDatabase.BeginTransaction()) {
                for (int c = index; c < RouteTable.ChildCount; c++)
                {
                    var rowForUpdate = (LinearLayout)RouteTable.GetChildAt(c);
                    routeItemUUID = (string)rowForUpdate.GetTag(Resource.String.RouteItemUUID);
                    var updRouteItem = MainDatabase.GetEntity <RouteItem>(routeItemUUID);
                    updRouteItem.Order     = c;
                    updRouteItem.IsSynced  = false;
                    updRouteItem.UpdatedAt = DateTimeOffset.Now;
                    rowForUpdate.SetTag(Resource.String.RouteItemOrder, c);
                    rowForUpdate.FindViewById <TextView>(Resource.Id.riOrderTV).Text = (c + 1).ToString();
                }
                trans.Commit();
            }

            if (pos != -1)
            {
                adapter.SwitchVisibility(pos);
            }
        }
Exemplo n.º 3
0
        void Clear_Click(object sender, EventArgs e)
        {
            //var transaction = MainDatabase.BeginTransaction();

            //MainDatabase.DeleteAttendancies();
            //MainDatabase.DeleteDistributions();
            //MainDatabase.DeleteFinanceData();
            //MainDatabase.DeleteSaleData();

            //MainDatabase.DeleteItems<FinanceDataByMonth>();
            //MainDatabase.DeleteItems<FinanceDataByQuarter>();
            //MainDatabase.DeleteItems<SaleDataByMonth>();
            //MainDatabase.DeleteItems<SaleDataByQuarter>();

            //MainDatabase.DeleteItems<CoterieData>();
            //MainDatabase.DeleteItems<PresentationData>();
            //MainDatabase.DeleteItems<Employee>();
            //MainDatabase.DeleteItems<PromotionData>();
            //MainDatabase.DeleteItems<CompetitorData>();
            //MainDatabase.DeleteItems<MessageData>();
            //MainDatabase.DeleteItems<ResumeData>();
            //MainDatabase.DeleteItems<PhotoData>();
            //MainDatabase.DeleteItems<Material>();
            //MainDatabase.DeleteItems<ListedHospital>();

            //MainDatabase.DeleteItems<RouteItem>();


            //transaction.Commit();

            MainDatabase.ClearDB();
            MainDatabase.Dispose();
        }
Exemplo n.º 4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);

            // Create your application here

            SetContentView(Resource.Layout.History);

            FindViewById <Button>(Resource.Id.haCloseB).Click += (sender, e) => {
                Finish();
            };

            var pharmacyUUID = Intent.GetStringExtra("UUID");

            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                return;
            }

            Pharmacy = MainDatabase.GetPharmacy(pharmacyUUID);
            FindViewById <TextView>(Resource.Id.haInfoTV).Text = string.Format("ИСТОРИЯ ВИЗИТОВ: {0}", Pharmacy.GetName());

            //				var date1 = FindViewById<TextView>(Resource.Id.htiDate1);
            //				date1.Text = DateTimeOffset.Now.Date.ToString("dd.MM.yy");
            //
            //				var date2 = FindViewById<TextView>(Resource.Id.htiDate2);
            //				date2.Text = DateTimeOffset.Now.Date.AddDays(7).Date.ToString("dd.MM.yy");

            Content   = FindViewById <LinearLayout>(Resource.Id.haContentLL);
            Table     = FindViewById <LinearLayout>(Resource.Id.haTable);
            TextViews = new Dictionary <string, TextView>();
        }
Exemplo n.º 5
0
        void CustomAction_Click(object sender, EventArgs e)
        {
            //var intent = new Intent(Intent.ActionGetContent);
            //intent.SetType("*/*");
            //intent.AddCategory(Intent.CategoryOpenable);
            //StartActivityForResult(intent, PICKFILE_REQUEST_CODE);
            string fileName       = "bd0712a3-a5e7-4704-b565-889f673a393b.realm";
            string dbFileLocation = Path.Combine(Helper.AppDir, fileName);

            if (File.Exists(dbFileLocation))
            {
                SDiag.Debug.WriteLine(dbFileLocation + " is Exists!");
            }

            if (File.Exists(MainDatabase.DBPath))
            {
                SDiag.Debug.WriteLine(MainDatabase.DBPath + " is Exists!");
                //var fi = new FileInfo(MainDatabase.DBPath);
                //var directory = fi.Directory.FullName;
                var newPath = Path.Combine(new FileInfo(MainDatabase.DBPath).Directory.FullName, fileName);
                if (!File.Exists(newPath))
                {
                    File.Copy(dbFileLocation, newPath, true);
                }

                if (File.Exists(newPath))
                {
                    SDiag.Debug.WriteLine(newPath + " is Exists!");
                    MainDatabase.Dispose();
                    Helper.C_DB_FILE_NAME = fileName;
                    MainDatabase.Username = Helper.Username;
                }
            }
        }
Exemplo n.º 6
0
        void RefreshPhotoList()
        {
            //llPhotoList.RemoveViews (1, llPhotoList.ChildCount - 1);
            PhotoTable.RemoveAllViews();

            int i = 0;

            foreach (var item in Photos)
            {
                i++;

                View vPhoto = Inflater.Inflate(Resource.Layout.PhotoTableItem, null);
                vPhoto.SetTag(Resource.String.PhotoPath, item.PhotoPath);
                vPhoto.FindViewById <TextView>(Resource.Id.ptiNumTV).Text = i.ToString();
                var photoType = MainDatabase.GetItem <PhotoType>(item.PhotoType);
                vPhoto.FindViewById <TextView>(Resource.Id.ptiTypeTV).Text = photoType.name;

                string drugBrand = (photoType.isNeedBrand) ? MainDatabase.GetItem <DrugBrand>(item.Brand).name : @"<не требуется>";
                vPhoto.FindViewById <TextView>(Resource.Id.ptiSubTypeTV).Text = drugBrand;

                vPhoto.FindViewById <TextView>(Resource.Id.ptiDateTimeTV).Text = item.Stamp.ToString("G");
                vPhoto.Click += (object sender, EventArgs e) => {
                    View view = (View)sender;
                    //Toast.MakeText(Activity, view.GetTag(Resource.String.PhotoPath).ToString(), ToastLength.Short).Show();
                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(Android.Net.Uri.Parse("file://" + view.GetTag(Resource.String.PhotoPath).ToString()), "image/*");
                    StartActivity(intent);
                };
                PhotoTable.AddView(vPhoto);
            }
        }
Exemplo n.º 7
0
        void Row_Drag(object sender, View.DragEventArgs e)
        {
            if (sender is LinearLayout)
            {
                var view = sender as LinearLayout;
                switch (e.Event.Action)
                {
                case DragAction.Started:
                    e.Handled = true;
                    break;

                case DragAction.Entered:
                    view.Visibility = ViewStates.Invisible;
                    break;

                case DragAction.Exited:
                    view.Visibility = ViewStates.Visible;
                    break;

                case DragAction.Ended:
                    view.Visibility = ViewStates.Visible;
                    e.Handled       = true;
                    break;

                case DragAction.Drop:
                    int clipedIndex = int.Parse(e.Event.ClipData.GetItemAt(0).Text);
                    var index       = (int)view.GetTag(Resource.String.RouteItemOrder);
                    if (clipedIndex != index)
                    {
                        var dragedView = RouteTable.GetChildAt(clipedIndex);
                        RouteTable.RemoveView(dragedView);
                        RouteTable.AddView(dragedView, index);
                        RouteTable.RemoveView(view);
                        RouteTable.AddView(view, clipedIndex);

                        using (var trans = MainDatabase.BeginTransaction()) {
                            for (int c = 0; c < RouteTable.ChildCount; c++)
                            {
                                var    rowForUpdate  = (LinearLayout)RouteTable.GetChildAt(c);
                                string routeItemUUID = (string)rowForUpdate.GetTag(Resource.String.RouteItemUUID);
                                var    updRouteItem  = MainDatabase.GetEntity <RouteItem>(routeItemUUID);
                                updRouteItem.Order     = c;
                                updRouteItem.IsSynced  = false;
                                updRouteItem.UpdatedAt = DateTimeOffset.Now;
                                rowForUpdate.SetTag(Resource.String.RouteItemOrder, c);
                                rowForUpdate.FindViewById <TextView>(Resource.Id.riOrderTV).Text = (c + 1).ToString();
                            }
                            trans.Commit();
                        }
                        //dragedView.SetTag(Resource.String.RouteItemOrder, index);
                        //view.SetTag(Resource.String.RouteItemOrder, clipedIndex);
                    }
                    view.Visibility = ViewStates.Visible;
                    e.Handled       = true;
                    break;
                }
            }
        }
Exemplo n.º 8
0
        public void SaveAllEmployees()
        {
            using (var trans = MainDatabase.BeginTransaction()) {
                for (int c = 0; c < EmployeeTable.ChildCount; c++)
                {
                    var row = EmployeeTable.GetChildAt(c);
                    if (row is LinearLayout)
                    {
                        row = (LinearLayout)row;
                        var isChanged = (bool)row.GetTag(Resource.String.IsChanged);
                        if (isChanged)
                        {
                            var employeeUUID = (string)row.GetTag(Resource.String.EmployeeUUID);
                            if (!string.IsNullOrEmpty(employeeUUID))
                            {
                                var employee = MainDatabase.GetEntity <Employee>(employeeUUID);
                                employee.UpdatedAt = DateTimeOffset.Now;

                                employee.Name = row.FindViewById <EditText>(Resource.Id.eetiNameET).Text;

                                var positionUUID = (string)row.FindViewById <Spinner>(Resource.Id.eetiPositionS).GetTag(Resource.String.PositionUUID);
                                if (!string.IsNullOrEmpty(positionUUID))
                                {
                                    employee.Position = positionUUID;
                                }

                                employee.IsCustomer = row.FindViewById <CheckBox>(Resource.Id.eetiIsCustomerCB).Checked;

                                /* BirthDate */
                                string             birthDate = row.FindViewById <EditText>(Resource.Id.eetiBirthDateET).Text;
                                DateTimeFormatInfo fmt       = new CultureInfo("ru-RU").DateTimeFormat;
                                if (!string.IsNullOrEmpty(birthDate))
                                {
                                    DateTimeOffset dtoBirthDate;
                                    if (DateTimeOffset.TryParse(birthDate, fmt, DateTimeStyles.AssumeUniversal, out dtoBirthDate))
                                    {
                                        employee.BirthDate = dtoBirthDate;
                                    }
                                }
                                /* ./BirthDate */

                                employee.Phone          = row.FindViewById <EditText>(Resource.Id.eetiPhoneET).Text;
                                employee.Email          = row.FindViewById <EditText>(Resource.Id.eetiEmailET).Text;
                                employee.CanParticipate = row.FindViewById <CheckBox>(Resource.Id.eetiCanParticipateCB).Checked;
                                employee.Comment        = row.FindViewById <EditText>(Resource.Id.eetiCommentET).Text;

                                if (!employee.IsManaged)
                                {
                                    MainDatabase.SaveEntity(trans, employee);
                                }
                            }
                        }
                    }
                }
                trans.Commit();
            }
        }
Exemplo n.º 9
0
        void InitViews()
        {
            #region Subway
            Subways        = MainDatabase.GetItems <Subway>();
            Subway.Adapter = new ArrayAdapter <string>(
                Activity, Android.Resource.Layout.SimpleDropDownItem1Line, Subways.Select(s => s.name).ToArray()
                );
            Subway.ItemClick += (sender, e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text   = ((AutoCompleteTextView)sender).Text;
                    var subway = Subways.SingleOrDefault(s => s.name.Equals(text));
                    if (subway != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.SubwayUUID, subway.uuid);
                    }
                }
            };
            #endregion

            #region Region
            Regions        = MainDatabase.GetItems <Region>();
            Region.Adapter = new ArrayAdapter <string>(
                Activity, Android.Resource.Layout.SimpleDropDownItem1Line, Regions.Select(r => r.name).ToArray()
                );
            Region.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text   = ((AutoCompleteTextView)sender).Text;
                    var region = Regions.SingleOrDefault(r => r.name.Equals(text));
                    if (region != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.RegionUUID, region.uuid);
                    }
                }
            };
            #endregion

            #region Net
            Nets        = MainDatabase.GetItems <Net>();
            Net.Adapter = new ArrayAdapter <string>(
                Activity, Android.Resource.Layout.SimpleDropDownItem1Line, Nets.Select(r => r.name).ToArray()
                );
            Net.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text = ((AutoCompleteTextView)sender).Text;
                    var net  = Nets.SingleOrDefault(n => n.name.Equals(text));
                    if (net != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.NetUUID, net.uuid);
                    }
                }
            };
            #endregion
        }
Exemplo n.º 10
0
        public override void OnResume()
        {
            base.OnResume();

            MondayTable.Adapter    = new RouteDayInWeekAdapter(Activity, MainDatabase.GetRouteItems(MondayDate));
            TuesdayTable.Adapter   = new RouteDayInWeekAdapter(Activity, MainDatabase.GetRouteItems(TuesdayDate));
            WednesdayTable.Adapter = new RouteDayInWeekAdapter(Activity, MainDatabase.GetRouteItems(WednesdayDate));
            ThursdayTable.Adapter  = new RouteDayInWeekAdapter(Activity, MainDatabase.GetRouteItems(ThursdayDate));
            FridayTable.Adapter    = new RouteDayInWeekAdapter(Activity, MainDatabase.GetRouteItems(FridayDate));
        }
Exemplo n.º 11
0
        void AddFinanceData(string pharmacyUUID, string skuUUID, DateTimeOffset period, float?sale, float?purchase, float?remain)
        {
            var financeData = MainDatabase.Create <FinanceData>();

            financeData.Pharmacy = pharmacyUUID;
            financeData.Period   = period;
            financeData.DrugSKU  = skuUUID;
            financeData.Sale     = sale;
            financeData.Purchase = purchase;
            financeData.Remain   = remain;
        }
Exemplo n.º 12
0
        void LoadCategories(RestClient client)
        {
            var request  = new RestRequest(@"Category?limit=300", Method.GET);
            var response = client.Execute <List <Category> >(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                SD.Debug.WriteLine(response.Data.Count);
                MainDatabase.SaveCategories(response.Data);
            }
        }
Exemplo n.º 13
0
        void LoadPromotions(RestClient client)
        {
            var request  = new RestRequest(@"Promotion?limit=300&populate=false", Method.GET);
            var response = client.Execute <List <Promotion> >(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                SD.Debug.WriteLine(string.Format(@"Получено Promotion {0}", response.Data.Count));
                MainDatabase.SaveItems(response.Data);
            }
        }
Exemplo n.º 14
0
        void RecreateAdapter()
        {
            ContractDatas = MainDatabase.GetPharmacyDatas <ContractData>(Pharmacy.UUID);

            if (ContractDatas.Count == 0)
            {
                return;
            }

            ContractTable.Adapter = new ContractAdapter(this, ContractDatas);
        }
Exemplo n.º 15
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            Dialog.SetCanceledOnTouchOutside(true);
            Dialog.SetTitle(@"Настройка фильтра");
            Dialog.Window.RequestFeature(WindowFeatures.NoTitle);

            View view = inflater.Inflate(Resource.Layout.FilterDialog, container, false);

            var prefs = Activity.GetSharedPreferences(C_FILTER_PREFS, FileCreationMode.Private);

            Subway = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdSubwayACTV);
            string subwayUUID = prefs.GetString(@"SUBWAY", string.Empty);

            if (!string.IsNullOrEmpty(subwayUUID))
            {
                Subway.Text = MainDatabase.GetItem <Subway>(subwayUUID).name;
                Subway.SetTag(Resource.String.SubwayUUID, subwayUUID);
            }
            Region = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdRegionACTV);
            string regionUUID = prefs.GetString(@"REGION", string.Empty);

            if (!string.IsNullOrEmpty(regionUUID))
            {
                Region.Text = MainDatabase.GetItem <Region>(regionUUID).name;
                Region.SetTag(Resource.String.RegionUUID, regionUUID);
            }
            Net = view.FindViewById <AutoCompleteTextView>(Resource.Id.fdNetACTV);
            string netUUID = prefs.GetString(@"NET", string.Empty);

            if (!string.IsNullOrEmpty(netUUID))
            {
                Net.Text = MainDatabase.GetItem <Net>(netUUID).name;
                Net.SetTag(Resource.String.NetUUID, netUUID);
            }
            Address      = view.FindViewById <EditText>(Resource.Id.fdAddressET);
            Address.Text = prefs.GetString(@"ADDRESS", string.Empty);

            InitViews();

            var close = view.FindViewById <Button>(Resource.Id.Close);

            close.Click += (sender, e) => {
                Dismiss();
            };

            var save = view.FindViewById <Button>(Resource.Id.Save);

            save.Click += Save_Click;

            return(view);
        }
Exemplo n.º 16
0
        void LoadDrugBrands(RestClient client)
        {
            var request  = new RestRequest(@"DrugBrand?limit=300&populate=false", Method.GET);
            var response = client.Execute <List <DrugBrand> >(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                SD.Debug.WriteLine(response.Data.Count);
                MainDatabase.SaveDrugBrands(response.Data);
            }
        }
Exemplo n.º 17
0
 void RecreateAdapter()
 {
     if (Employees != null && Employees.Count > 0)
     {
         EmployeeTable.RemoveViews(1, Employees.Count);
     }
     Employees = MainDatabase.GetPharmacyDatas <Employee>(Pharmacy.UUID);
     foreach (var employee in Employees)
     {
         AddEmployeeToTable(employee);
     }
 }
Exemplo n.º 18
0
        public static void Dispose()
        {
            if (Me == null)
            {
                return;
            }

            if ((Me.DB != null) && (!Me.DB.IsClosed))
            {
                Me.DB.Close();
            }
            Me = null;
        }
Exemplo n.º 19
0
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var pharmacyUUID = Arguments.GetString(C_PHARMACY_UUID);

            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                return;
            }

            Pharmacy = MainDatabase.GetPharmacy(pharmacyUUID);
        }
Exemplo n.º 20
0
        void RefreshView()
        {
            Count = 0;

            Count += MainDatabase.CountItemsToSync <Attendance>();
            Count += MainDatabase.CountItemsToSync <CompetitorData>();
            Count += MainDatabase.CountItemsToSync <ContractData>();
            Count += MainDatabase.CountItemsToSync <CoterieData>();
            Count += MainDatabase.CountItemsToSync <DistributionData>();
            Count += MainDatabase.CountItemsToSync <Pharmacy>();
            Count += MainDatabase.CountItemsToSync <Employee>();
            Count += MainDatabase.CountItemsToSync <ExcludeRouteItem>();

            Count += MainDatabase.CountItemsToSync <GPSData>();

            Count += MainDatabase.CountItemsToSync <Hospital>();
            Count += MainDatabase.CountItemsToSync <HospitalData>();

            Count += MainDatabase.CountItemsToSync <Entities.Message>();
            Count += MainDatabase.CountItemsToSync <MessageData>();
            //var photoDatas = MainDatabase.GetItemsToSync<PhotoData>();

            Count += MainDatabase.CountItemsToSync <PresentationData>();
            Count += MainDatabase.CountItemsToSync <PromotionData>();
            Count += MainDatabase.CountItemsToSync <ResumeData>();
            Count += MainDatabase.CountItemsToSync <RouteItem>();


            var toSyncCount = FindViewById <TextView>(Resource.Id.saSyncEntitiesCount);

            toSyncCount.Text = string.Format("Необходимо синхронизировать {0} объектов", Count);

            var toUpdateCount = FindViewById <TextView>(Resource.Id.saUpdateEntitiesCount);

            toUpdateCount.Text = string.Format("Необходимо обновить {0} объектов", 0);

            var photoCount = FindViewById <TextView>(Resource.Id.saSyncPhotosCount);

            photoCount.Text = string.Format("Необходимо выгрузить {0} фото", MainDatabase.CountItemsToSync <PhotoData>());


            CancelSource = new CancellationTokenSource();
            CancelToken  = CancelSource.Token;
            CheckMaterialFiles();

            CSForLibraryFiles = new CancellationTokenSource();
            CTForLibraryFiles = CSForLibraryFiles.Token;
            CheckLibraryFiles();
        }
Exemplo n.º 21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Material);

            var materialUUID = Intent.GetStringExtra(C_MATERIAL_UUID);

            if (string.IsNullOrEmpty(materialUUID))
            {
                return;
            }

            var material = MainDatabase.GetItem <Material>(materialUUID);

            FindViewById <TextView>(Resource.Id.mMaterialTV).Text = material.name;
        }
Exemplo n.º 22
0
        void SetNet(int index)
        {
            if ((Nets != null) && (Nets.Count > 0))
            {
                if (NetUUID != Nets[index].uuid)
                {
                    NetUUID      = Nets[index].uuid;
                    NetName.Text = Nets[index].name;

                    // Init Contracts
                    ContractsNames.Text     = string.Empty;
                    Contracts               = MainDatabase.GetItems <Contract>().Where(c => c.net == NetUUID).ToList();
                    ContractsChoice.Enabled = (Contracts.Count > 0);

                    //ContractsChoice.Click -= ContractsChoice_Click;
                }
            }
        }
Exemplo n.º 23
0
        public void OnAttendanceStop(Transaction openedTransaction, Attendance current)
        {
            if (openedTransaction == null)
            {
                throw new ArgumentNullException(nameof(openedTransaction));
            }

            if (current == null)
            {
                throw new ArgumentNullException(nameof(current));
            }

            var pharmacy = MainDatabase.GetEntity <Pharmacy>(Pharmacy.UUID);

            pharmacy.LastAttendance     = current.UUID;
            pharmacy.LastAttendanceDate = current.When;
            // TODO: Сделать глобальной настройкой
            pharmacy.NextAttendanceDate = Agent == null?current.When.AddDays(14) : current.When.AddDays(Agent.weeksInRout * 7);
        }
Exemplo n.º 24
0
        public void OnAttendanceStop(Transaction openedTransaction, Attendance current)
        {
            if (openedTransaction == null)
            {
                throw new ArgumentNullException(nameof(openedTransaction));
            }

            if (current == null)
            {
                throw new ArgumentNullException(nameof(current));
            }

            foreach (var photo in Photos)
            {
                var photoData = MainDatabase.CreateData <PhotoData>(current.UUID);
                photoData.PhotoType = photo.PhotoType;
                photoData.Brand     = photo.Brand;
                photoData.Stamp     = photo.Stamp;
                photoData.PhotoPath = photo.PhotoPath;
                photoData.Latitude  = photo.Latitude;
                photoData.Longitude = photo.Longitude;
            }
        }
Exemplo n.º 25
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            base.OnCreateView(inflater, container, savedInstanceState);

            View view = inflater.Inflate(Resource.Layout.EmployeeFragment, container, false);

            var pharmacyUUID = Arguments.GetString(C_PHARMACY_UUID);

            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                return(view);
            }

            Pharmacy  = MainDatabase.GetEntity <Pharmacy>(pharmacyUUID);
            Positions = MainDatabase.GetItems <Position>();

            EmployeeTable = view.FindViewById <LinearLayout>(Resource.Id.efEmployeeTable);

            var header = Activity.LayoutInflater.Inflate(Resource.Layout.EmployeeEditTableHeader, EmployeeTable, false);

            EmployeeTable.AddView(header);

            view.FindViewById <Button>(Resource.Id.efAddB).Click += (sender, e) => {
                using (var trans = MainDatabase.BeginTransaction()) {
                    var newEmployee = MainDatabase.CreateEmployee(Pharmacy.UUID);
                    trans.Commit();

                    Employees.Add(newEmployee);
                    AddEmployeeToTable(newEmployee);
                }
            };

            return(view);
        }
Exemplo n.º 26
0
        protected override void OnResume()
        {
            base.OnResume();
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            ReportData = MainDatabase.GetProfileReportData(Dates);

            int weeksCount = 14;
            var summer     = (LinearLayout)LayoutInflater.Inflate(Resource.Layout.AttendanceByWeekTableHeader, Table, false);

            (summer.GetChildAt(0) as TextView).Text = @"Итого";
            for (int w = 0; w < weeksCount; w++)
            {
                var d     = Dates[w].UtcDateTime.Date;
                var key   = d.Year * 100 + Helper.GetIso8601WeekOfYear(d);
                var hView = summer.GetChildAt(w + 1);
                if (hView is TextView)
                {
                    int sum = 0;
                    foreach (var item in ReportData)
                    {
                        sum += item.Value[key];
                    }

                    (hView as TextView).Text = sum.ToString();
                }
            }
            Content.AddView(summer, 2);

            Table.Adapter = new AttendanceByWeekAdapter(this, ReportData, Dates);

            watch.Stop();

            Console.WriteLine("OnResume: {0}", watch.ElapsedMilliseconds);
        }
Exemplo n.º 27
0
        async void CheckLibraryFiles()
        {
            var client = new RestClient(HOST_URL);
            //var client = new RestClient("http://sbl-crm-project-pafik13.c9users.io:8080/");
            var request = new RestRequest("/LibraryFile?type=for_hospital&populate=false", Method.GET);

            var response = await client.ExecuteGetTaskAsync <List <LibraryFile> >(request);

            if (!CTForLibraryFiles.IsCancellationRequested)
            {
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                    SDiag.Debug.WriteLine("MaterialFile: {0}", response.Data.Count);
                    LibraryFiles.Clear();
                    foreach (var item in response.Data)
                    {
                        if (!MainDatabase.IsSavedBefore <LibraryFile>(item.uuid))
                        {
                            if (!string.IsNullOrEmpty(item.s3Location))
                            {
                                LibraryFiles.Add(item);
                            }
                        }
                    }

                    RunOnUiThread(() => {
                        int count = MaterialFiles.Count + WorkTypes.Count + LibraryFiles.Count;
                        FindViewById <TextView>(Resource.Id.saUpdateEntitiesCount).Text = string.Format("Необходимо обновить {0} объектов", count);
                    });
                    break;
                }
                SDiag.Debug.WriteLine(response.StatusDescription);
            }
        }
Exemplo n.º 28
0
        //SuggestClient Api;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            // Create your application here
            SetContentView(Resource.Layout.Pharmacy);

            FindViewById <Button>(Resource.Id.paCloseB).Click += (s, e) => {
                Finish();
            };

            FindViewById <Button>(Resource.Id.paSaveB).Click += (s, e) => {
                var transaction = MainDatabase.BeginTransaction();

                Pharmacy item;
                if (Pharmacy == null)
                {
                    item           = MainDatabase.Create2 <Pharmacy>();
                    item.CreatedAt = DateTimeOffset.Now;

                    /* Contracts */
                    if (!string.IsNullOrEmpty(ContractsNames.Text))
                    {
                        var ll            = ContractsNames.Parent as LinearLayout;
                        var contractUUIDs = (string)ll.GetTag(Resource.String.ContractUUIDs);
                        if (!string.IsNullOrEmpty(contractUUIDs))
                        {
                            foreach (var contract in contractUUIDs.Split(';'))
                            {
                                var contractData = MainDatabase.Create <ContractData>();
                                contractData.Pharmacy = item.UUID;
                                contractData.Contract = contract;
                            }
                        }
                    }
                    /* ./Contracts */
                }
                else
                {
                    item = Pharmacy;

                    /* Contracts */
                    if (string.IsNullOrEmpty(ContractsNames.Text))
                    {
                        var contractDatas = MainDatabase.GetPharmacyDatas <ContractData>(item.UUID);
                        foreach (var contractData in contractDatas)
                        {
                            MainDatabase.DeleteEntity(transaction, contractData);;
                        }
                        contractDatas = null;
                    }
                    else
                    {
                        var ll            = ContractsNames.Parent as LinearLayout;
                        var contractUUIDs = (string)ll.GetTag(Resource.String.ContractUUIDs);
                        if (!string.IsNullOrEmpty(contractUUIDs))
                        {
                            var contracts     = contractUUIDs.Split(';');
                            var contractDatas = MainDatabase.GetPharmacyDatas <ContractData>(item.UUID);
                            foreach (var contractData in contractDatas)
                            {
                                MainDatabase.DeleteEntity(transaction, contractData);
                            }
                            contractDatas = null;
                            foreach (var contract in contractUUIDs.Split(';'))
                            {
                                var contractData = MainDatabase.Create2 <ContractData>();
                                contractData.Pharmacy = item.UUID;
                                contractData.Contract = contract;
                            }
                        }
                    }
                    /* ./Contracts */
                }

                item.UpdatedAt = DateTimeOffset.Now;
                item.IsSynced  = false;
                item.SetState((PharmacyState)State.SelectedItemPosition);
                item.Brand      = FindViewById <EditText>(Resource.Id.paBrandET).Text;
                item.NumberName = FindViewById <EditText>(Resource.Id.paNumberNameET).Text;
                item.LegalName  = FindViewById <EditText>(Resource.Id.paLegalNameET).Text;

                if (string.IsNullOrEmpty(NetName.Text))
                {
                    item.Net = string.Empty;
                }
                else
                {
                    item.Net = NetUUID;
                }

                var address = FindViewById <AutoCompleteTextView>(Resource.Id.paAddressACTV);
                item.Address = address.Text;
                bool isChanged = (bool)address.GetTag(Resource.String.IsChanged);
                if (isChanged)
                {
                    item.AddressFiasId = (string)address.GetTag(Resource.String.fias_id);
                    item.AddressQCGeo  = (string)address.GetTag(Resource.String.qc_geo);
                    item.AddressGeoLat = (string)address.GetTag(Resource.String.geo_lat);
                    item.AddressGeoLon = (string)address.GetTag(Resource.String.geo_lon);
                }

                if (string.IsNullOrEmpty(Subway.Text))
                {
                    item.Subway = string.Empty;
                }
                else
                {
                    var subwayUUID = (string)Subway.GetTag(Resource.String.SubwayUUID);
                    if (!string.IsNullOrEmpty(subwayUUID))
                    {
                        item.Subway = subwayUUID;
                    }
                }

                if (string.IsNullOrEmpty(Region.Text))
                {
                    item.Region = string.Empty;
                }
                else
                {
                    var regionUUID = (string)Region.GetTag(Resource.String.RegionUUID);
                    if (!string.IsNullOrEmpty(regionUUID))
                    {
                        item.Region = regionUUID;
                    }
                }

                item.Phone = FindViewById <EditText>(Resource.Id.paPhoneET).Text;

                if (string.IsNullOrEmpty(Place.Text))
                {
                    item.Place = string.Empty;
                }
                else
                {
                    var placeUUID = (string)Place.GetTag(Resource.String.PlaceUUID);
                    if (!string.IsNullOrEmpty(placeUUID))
                    {
                        item.Place = placeUUID;
                    }
                }

                if (Category.SelectedItemPosition > 0)
                {
                    item.Category = Categories[Category.SelectedItemPosition].uuid;
                }
                else
                {
                    item.Category = string.Empty;
                }
                //if (string.IsNullOrEmpty(Category.Text)) {
                //	item.Category = string.Empty;
                //} else {
                //	var categoryUUID = (string)Category.GetTag(Resource.String.CategoryUUID);
                //	if (!string.IsNullOrEmpty(categoryUUID)) {
                //		item.Category = categoryUUID;
                //	}
                //}
                item.TurnOver = Helper.ToInt(FindViewById <EditText>(Resource.Id.paTurnOverET).Text);
                item.Comment  = FindViewById <EditText>(Resource.Id.paCommentET).Text;

                if (!item.IsManaged)
                {
                    MainDatabase.SaveEntity(transaction, item);
                }

                transaction.Commit();

                //var sync = new SyncItem() {
                //	Path = @"Pharmacy",
                //	ObjectUUID = Pharmacy.UUID,
                //	JSON = JsonConvert.SerializeObject(Pharmacy)
                //};

                //MainDatabase.AddToQueue(sync);

                //StartService(new Intent("com.xamarin.SyncService"));
                GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
                .Edit()
                .PutString(MainActivity.C_SAVED_PHARMACY_UUID, item.UUID)
                .Commit();

                Finish();
            };

            //Api = new SuggestClient(Secret.DadataApiToken, Secret.DadataApiURL);


            #region State
            State  = FindViewById <Spinner>(Resource.Id.paStateS);
            States = MainDatabase.GetStates();
            var stateAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, States.ToArray());
            stateAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            State.Adapter = stateAdapter;
            #endregion

            #region Net
            Nets    = MainDatabase.GetNets();
            NetName = FindViewById <AutoCompleteTextView>(Resource.Id.paNetACTV);
            var netChoiceButton = FindViewById <Button>(Resource.Id.paNetB);
            netChoiceButton.Click += (object sender, EventArgs e) => {
                new AlertDialog.Builder(this)
                .SetTitle("Аптечная сеть")
                .SetCancelable(true)
                .SetItems(Nets.Select(item => item.name).ToArray(), (caller, arguments) => {
                    SetNet(arguments.Which);
                    //Toast.MakeText(this, @"Selected " + arguments.Which, ToastLength.Short).Show();
                })
                .Show();
            };
            #endregion

            ContractsNames         = FindViewById <AutoCompleteTextView>(Resource.Id.paContractsACTV);
            ContractsChoice        = FindViewById <Button>(Resource.Id.paContractsB);
            ContractsChoice.Click += ContractsChoice_Click;

            Address = FindViewById <AutoCompleteTextView>(Resource.Id.paAddressACTV);
            Address.SetTag(Resource.String.IsChanged, false);

            Subway = FindViewById <AutoCompleteTextView>(Resource.Id.paSubwayACTV);

            Region = FindViewById <AutoCompleteTextView>(Resource.Id.paRegionACTV);

            Place = FindViewById <AutoCompleteTextView>(Resource.Id.paPlaceACTV);

            //Category = FindViewById<AutoCompleteTextView>(Resource.Id.paCategoryACTV);

            #region Category
            Category   = FindViewById <Spinner>(Resource.Id.paCategoryS);
            Categories = new List <Category>();
            Categories.Add(new Category {
                name = @"Выберите категорию!", uuid = Guid.Empty.ToString()
            });
            Categories.AddRange(MainDatabase.GetItems <Category>());;
            var categoryAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, Categories.Select(cat => cat.name).ToArray());
            categoryAdapter.SetDropDownViewResource(Resource.Layout.SpinnerItem);
            Category.Adapter = categoryAdapter;
            #endregion

            var pharmacyUUID = Intent.GetStringExtra("UUID");
            if (string.IsNullOrEmpty(pharmacyUUID))
            {
                var shared    = GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private);
                var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);
                try {
                    var agent = MainDatabase.GetItem <Agent>(agentUUID);
                    Address.Text = agent.city;
                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }

                FindViewById <TextView>(Resource.Id.paInfoTV).Text = @"ДОБАВЛЕНИЕ НОВОЙ АПТЕКИ";
                FindViewById <TableRow>(Resource.Id.paRowLastAttendance).Visibility     = ViewStates.Gone;
                FindViewById <TableRow>(Resource.Id.paRowNextAttendanceDate).Visibility = ViewStates.Gone;

                InitViews();
                return;
            }

            Pharmacy = MainDatabase.GetEntity <Pharmacy>(pharmacyUUID);

            FindViewById <TextView>(Resource.Id.paInfoTV).Text = "АПТЕКА : " + Pharmacy.GetName();

            FindViewById <TextView>(Resource.Id.paUUIDTV).Text = Pharmacy.UUID;

            State.SetSelection((int)Pharmacy.GetState());
            FindViewById <EditText>(Resource.Id.paBrandET).Text      = Pharmacy.Brand;
            FindViewById <EditText>(Resource.Id.paNumberNameET).Text = Pharmacy.NumberName;
            FindViewById <EditText>(Resource.Id.paLegalNameET).Text  = Pharmacy.LegalName;

            //NetName.Text = string.IsNullOrEmpty(Pharmacy.Net) ?
            //	string.Empty : MainDatabase.GetNet(Pharmacy.Net).name;
            //NetUUID = Pharmacy.Net;

            if (!string.IsNullOrEmpty(Pharmacy.Net))
            {
                SetNet(Nets.FindIndex(net => string.Compare(net.uuid, Pharmacy.Net) == 0));
            }

            ContractDatas = MainDatabase.GetPharmacyDatas <ContractData>(Pharmacy.UUID);
            if (ContractDatas.Count > 0)
            {
                ContractsNames.Text = string.Join(", ", ContractDatas.Select(cd => MainDatabase.GetItem <Contract>(cd.Contract).name).ToArray());
                var ll = ContractsNames.Parent as LinearLayout;
                ll.SetTag(Resource.String.ContractUUIDs,
                          string.Join(@";", ContractDatas.Select(cd => cd.Contract).ToArray())
                          );
            }
            Address.Text = Pharmacy.Address;

            Subway.Text = string.IsNullOrEmpty(Pharmacy.Subway) ?
                          string.Empty : MainDatabase.GetItem <Subway>(Pharmacy.Subway).name;

            Region.Text = string.IsNullOrEmpty(Pharmacy.Region) ?
                          string.Empty : MainDatabase.GetItem <Region>(Pharmacy.Region).name;

            FindViewById <EditText>(Resource.Id.paPhoneET).Text = Pharmacy.Phone;

            Place.Text = string.IsNullOrEmpty(Pharmacy.Place) ?
                         string.Empty : MainDatabase.GetItem <Place>(Pharmacy.Place).name;

            //Category.Text = string.IsNullOrEmpty(Pharmacy.Category) ?
            //	string.Empty : MainDatabase.GetItem<Category>(Pharmacy.Category).name;
            if (!string.IsNullOrEmpty(Pharmacy.Category))
            {
                Category.SetSelection(Categories.FindIndex(cat => string.Compare(cat.uuid, Pharmacy.Category) == 0));
            }

            FindViewById <EditText>(Resource.Id.paTurnOverET).Text = Pharmacy.TurnOver.HasValue ?
                                                                     Pharmacy.TurnOver.Value.ToString() : string.Empty;

            FindViewById <TextView>(Resource.Id.paLastAttendanceTV).Text = Pharmacy.LastAttendanceDate.HasValue ?
                                                                           Pharmacy.LastAttendanceDate.Value.ToString(@"dd.MM.yyyy") : @"<нет визита>";

            FindViewById <TextView>(Resource.Id.paNextAttendanceDateTV).Text = Pharmacy.NextAttendanceDate.HasValue ?
                                                                               Pharmacy.NextAttendanceDate.Value.ToString(@"dd.MM.yyyy") : DateTimeOffset.Now.ToString(@"dd.MM.yyyy");

            FindViewById <EditText>(Resource.Id.paCommentET).Text = Pharmacy.Comment;


            InitViews();
        }
Exemplo n.º 29
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_screen_slide);

            PharmacyUUID = Intent.GetStringExtra("UUID");
            if (string.IsNullOrEmpty(PharmacyUUID))
            {
                return;
            }

            AttendanceLast = MainDatabase.GetAttendaces(PharmacyUUID).OrderByDescending(i => i.When).FirstOrDefault();
            var attendanceLastUUID = AttendanceLast == null ? string.Empty : AttendanceLast.UUID;

            Materials = MainDatabase.GetItems <Material>();

            FragmentTitle      = FindViewById <TextView>(Resource.Id.aaTitleTV);
            FragmentTitle.Text = @"АПТЕКА";

            Pager = FindViewById <ViewPager>(Resource.Id.aaContainerVP);
            Pager.AddOnPageChangeListener(this);
            Pager.OffscreenPageLimit = 3;
            Pager.Adapter            = new AttendancePagerAdapter(SupportFragmentManager, PharmacyUUID, attendanceLastUUID);

            var btnStartStop = FindViewById <Button>(Resource.Id.aaStartOrStopAttendanceB);

            btnStartStop.Click += (sender, e) =>
            {
                if (!IsLocationActive() || !IsInternetActive())
                {
                    return;
                }

                if (AttendanceStart == null)
                {
                    AttendanceStart = DateTimeOffset.Now;

                    // Location
                    Locations = new List <Location>();

                    LocMgr = GetSystemService(LocationService) as LocationManager;
                    var locationCriteria = new Criteria();
                    locationCriteria.Accuracy         = Accuracy.Coarse;
                    locationCriteria.PowerRequirement = Power.Medium;
                    string locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
                    System.Diagnostics.Debug.Print("Starting location updates with " + locationProvider);
                    LocMgr.RequestLocationUpdates(locationProvider, 5000, 1, this);
                    // !Location

                    if (Pager.CurrentItem == 2)
                    {
                        FragmentTitle.Text = @"СОБИРАЕМАЯ ИНФОРМАЦИЯ";
                    }

                    if (Pager.CurrentItem == 3)
                    {
                        FragmentTitle.Text = @"ФОТО НА ВИЗИТЕ";
                    }

                    for (int f = 0; f < C_NUM_PAGES; f++)
                    {
                        var fragment = GetFragment(f);
                        if (fragment is IAttendanceControl)
                        {
                            (fragment as IAttendanceControl).OnAttendanceStart(AttendanceStart);
                        }
                    }

                    Close.Visibility = ViewStates.Invisible;

                    Contracts.Visibility = ViewStates.Visible;

                    Finance.Visibility = ViewStates.Visible;
                    var financeParams = Finance.LayoutParameters as RelativeLayout.LayoutParams;
                    financeParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaContractsIV);

                    History.Visibility = ViewStates.Visible;
                    var historyParams = History.LayoutParameters as RelativeLayout.LayoutParams;
                    historyParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaFinanceIV);

                    Material.Visibility = ViewStates.Visible;
                    var materialParams = Material.LayoutParameters as RelativeLayout.LayoutParams;
                    materialParams.AddRule(LayoutRules.LeftOf, Resource.Id.aaHistoryIV);

                    var button = sender as Button;
                    button.SetBackgroundResource(Resource.Color.Deep_Orange_500);
                    button.Text = "ЗАКОНЧИТЬ ВИЗИТ";
                    return;
                }

                if ((DateTimeOffset.Now - AttendanceStart.Value).TotalSeconds < 30)
                {
                    return;
                }

                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                var fragmentTransaction = SupportFragmentManager.BeginTransaction();
                var prev = SupportFragmentManager.FindFragmentByTag(LockDialog.TAG);
                if (prev != null)
                {
                    fragmentTransaction.Remove(prev);
                }
                fragmentTransaction.AddToBackStack(null);

                var lockDialog = LockDialog.Create("Идет сохранение данных...", Resource.Color.Deep_Orange_500);
                lockDialog.Cancelable = false;
                lockDialog.Show(fragmentTransaction, LockDialog.TAG);

                LocMgr.RemoveUpdates(this);

                new Task(() => {
                    Thread.Sleep(2000);                     // иначе не успеет показаться диалог

                    RunOnUiThread(() => {
                        var transaction     = MainDatabase.BeginTransaction();
                        var attendance      = MainDatabase.Create2 <Attendance>();
                        attendance.Pharmacy = PharmacyUUID;
                        attendance.When     = AttendanceStart.Value;
                        attendance.Duration = (DateTimeOffset.Now - AttendanceStart.Value).TotalMilliseconds;

                        foreach (var location in Locations)
                        {
                            var gps                  = MainDatabase.Create2 <GPSData>();
                            gps.Attendance           = attendance.UUID;
                            gps.Accuracy             = location.Accuracy;
                            gps.Altitude             = location.Altitude;
                            gps.Bearing              = location.Bearing;
                            gps.ElapsedRealtimeNanos = location.ElapsedRealtimeNanos;
                            gps.IsFromMockProvider   = location.IsFromMockProvider;
                            gps.Latitude             = location.Latitude;
                            gps.Longitude            = location.Longitude;
                            gps.Provider             = location.Provider;
                            gps.Speed                = location.Speed;
                        }

                        // Оповещаем фрагменты о завершении визита
                        for (int f = 0; f < C_NUM_PAGES; f++)
                        {
                            var fragment = GetFragment(f);
                            if (fragment is IAttendanceControl)
                            {
                                (fragment as IAttendanceControl).OnAttendanceStop(transaction, attendance);
                            }
                        }

                        transaction.Commit();

                        //if (lockDialog != null) {
                        //	lockDialog.DismissAllowingStateLoss();
                        //}

                        Finish();
                    });
                }).Start();
            };
            // TODO: uncomment
            if (AttendanceLast != null)
            {
                if (AttendanceLast.When.Date == DateTimeOffset.UtcNow.Date)
                {
                    btnStartStop.Visibility = ViewStates.Gone;
                }
            }

            Close        = FindViewById <Button>(Resource.Id.aaCloseB);
            Close.Click += (sender, e) =>
            {
                Finish();
            };

            Contracts        = FindViewById <ImageView>(Resource.Id.aaContractsIV);
            Contracts.Click += (sender, e) => {
                var contractActivity = new Intent(this, typeof(ContractActivity));
                contractActivity.PutExtra(ContractActivity.C_PHARMACY_UUID, PharmacyUUID);
                StartActivity(contractActivity);
            };

            Finance        = FindViewById <ImageView>(Resource.Id.aaFinanceIV);
            Finance.Click += (sender, e) => {
                var financeActivity = new Intent(this, typeof(FinanceActivity));
                financeActivity.PutExtra(@"UUID", PharmacyUUID);
                financeActivity.PutExtra(FinanceActivity.C_IS_CAN_ADD, false);
                StartActivity(financeActivity);
            };

            History        = FindViewById <ImageView>(Resource.Id.aaHistoryIV);
            History.Click += (sender, e) => {
                var historyActivity = new Intent(this, typeof(HistoryActivity));
                historyActivity.PutExtra(@"UUID", PharmacyUUID);
                StartActivity(historyActivity);
            };

            Material        = FindViewById <ImageView>(Resource.Id.aaMaterialIV);
            Material.Click += (sender, e) => {
                if (Materials.Count == 0)
                {
                    return;
                }

                var materialItems = new List <MaterialItem>();
                var materialFiles = MainDatabase.GetItems <MaterialFile>();
                foreach (var mf in materialFiles)
                {
                    var file = new Java.IO.File(Helper.MaterialDir, mf.fileName);
                    if (file.Exists())
                    {
                        var found = Materials.FirstOrDefault(m => m.uuid == mf.material);
                        if (found != null)
                        {
                            materialItems.Add(new MaterialItem(found.name, file));
                        }
                    }
                }

                if (materialItems.Count == 0)
                {
                    return;
                }

                new AlertDialog.Builder(this)
                .SetTitle("Выберите материал для показа:")
                .SetCancelable(true)
                .SetItems(
                    materialItems.Select(item => item.MaterialName).ToArray(),
                    (caller, arguments) => {
                    var intent = new Intent(Intent.ActionView);
                    var uri    = Android.Net.Uri.FromFile(materialItems[arguments.Which].FilePath);
                    intent.SetDataAndType(uri, "application/pdf");
                    intent.SetFlags(ActivityFlags.NoHistory);
                    StartActivity(intent);
                })
                .Show();
            };
        }
Exemplo n.º 30
0
        void InitViews()
        {
            #region Address
            //Address.AfterTextChanged += (object sender, Android.Text.AfterTextChangedEventArgs e) => {
            //if (Address.IsPerformingCompletion) return;

            //if (Address.Text.Contains(" ")) {
            //	var suggestions = new List<SuggestAddressResponse.Suggestions>();
            //	try {
            //		var response = Api.QueryAddress(Address.Text);
            //		suggestions = response.suggestionss;
            //	} catch (Exception ex) {
            //		System.Diagnostics.Debug.WriteLine(ex.Message);
            //	}
            //	Address.Adapter = new AddressSuggestionAdapter(this, suggestions);

            //	if (Address.IsShown) {
            //		Address.DismissDropDown();
            //	}
            //	Address.ShowDropDown();
            //}
            //};
            //Address.ItemClick += (sender, e) => {
            //	var item = (((AutoCompleteTextView)sender).Adapter as AddressSuggestionAdapter)[e.Position];
            //	((AutoCompleteTextView)sender).SetTag(Resource.String.IsChanged, true);
            //	((AutoCompleteTextView)sender).SetTag(Resource.String.fias_id, item.data.fias_id);
            //	((AutoCompleteTextView)sender).SetTag(Resource.String.qc_geo, item.data.qc_geo);
            //	((AutoCompleteTextView)sender).SetTag(Resource.String.geo_lat, item.data.geo_lat);
            //	((AutoCompleteTextView)sender).SetTag(Resource.String.geo_lon, item.data.geo_lon);
            //};
            #endregion

            #region Subway
            Subways        = MainDatabase.GetItems <Subway>();
            Subway.Adapter = new ArrayAdapter <string>(
                this, Android.Resource.Layout.SimpleDropDownItem1Line, Subways.Select(s => s.name).ToArray()
                );
            Subway.ItemClick += (sender, e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text   = ((AutoCompleteTextView)sender).Text;
                    var subway = Subways.SingleOrDefault(s => s.name.Equals(text));
                    if (subway != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.SubwayUUID, subway.uuid);
                    }
                }
            };
            #endregion

            #region Region
            Regions        = MainDatabase.GetItems <Region>();
            Region.Adapter = new ArrayAdapter <string>(
                this, Android.Resource.Layout.SimpleDropDownItem1Line, Regions.Select(r => r.name).ToArray()
                );
            Region.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text   = ((AutoCompleteTextView)sender).Text;
                    var region = Regions.SingleOrDefault(r => r.name.Equals(text));
                    if (region != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.RegionUUID, region.uuid);
                    }
                }
            };
            #endregion

            #region Place
            Places        = MainDatabase.GetItems <Place>();
            Place.Adapter = new ArrayAdapter <string>(
                this, Android.Resource.Layout.SimpleDropDownItem1Line, Places.Select(x => x.name).ToArray()
                );
            Place.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                if (sender is AutoCompleteTextView)
                {
                    var text  = ((AutoCompleteTextView)sender).Text;
                    var place = Places.SingleOrDefault(p => p.name.Equals(text));
                    if (place != null)
                    {
                        ((AutoCompleteTextView)sender).SetTag(Resource.String.PlaceUUID, place.uuid);
                    }
                }
            };
            #endregion

            //#region Category
            //Categories = MainDatabase.GetItems<Category>();
            //Category.Adapter = new ArrayAdapter<string>(
            //	this, Android.Resource.Layout.SimpleDropDownItem1Line, Categories.Select(c => c.name).ToArray()
            //);
            //Category.FocusChange += (sender, e) => {
            //	if (Categories.Count > 0 && Categories.Count < 10) {
            //		if (sender is AutoCompleteTextView) {
            //			var actv = (AutoCompleteTextView)sender;
            //			if (actv.HasFocus) {
            //				actv.ShowDropDown();
            //			}
            //		}
            //	}
            //};
            //Category.AfterTextChanged += (sender, e) => {
            //	if (Categories.Count > 0 && Categories.Count < 10) {
            //		if (sender is AutoCompleteTextView) {
            //			var actv = (AutoCompleteTextView)sender;
            //			if (actv.HasFocus) {
            //				actv.ShowDropDown();
            //			}
            //		}
            //	}
            //};
            //Category.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
            //	if (sender is AutoCompleteTextView) {
            //		var text = ((AutoCompleteTextView)sender).Text;
            //		var category = Categories.SingleOrDefault(c => c.name.Equals(text));
            //		if (category != null) {
            //			((AutoCompleteTextView)sender).SetTag(Resource.String.CategoryUUID, category.uuid);
            //		}
            //	}
            //};
            //#endregion
        }