Esempio n. 1
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);
            }
        }
Esempio n. 2
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();
            }
        }
Esempio n. 3
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;
                }
            }
        }
Esempio n. 4
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();
            }
        }
Esempio n. 5
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);
        }
        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();
            };
        }
        //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();
        }
Esempio n. 8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

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

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

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

            PharmacyTable            = FindViewById <ListView>(Resource.Id.raPharmacyTable);
            PharmacyTable.ItemClick += (sender, e) => {
                var ll      = (ListView)sender;
                var adapter = (RoutePharmacyAdapter)ll.Adapter;
                adapter.SwitchVisibility(e.Position);

                var row = LayoutInflater.Inflate(Resource.Layout.RouteItem, RouteTable, false);
                row.SetTag(Resource.String.Position, e.Position);

                RouteSearchItem item;
                if (string.IsNullOrEmpty(SearchEditor.Text))
                {
                    item = RouteSearchItems[e.Position];
                }
                else
                {
                    item = SearchedItems[e.Position];
                }

                //TODO: rename vars
                using (var trans = MainDatabase.BeginTransaction()){
                    var newRouteItem = MainDatabase.Create2 <RouteItem>();
                    newRouteItem.Pharmacy = item.UUID;
                    newRouteItem.Order    = RouteTable.ChildCount;
                    newRouteItem.Date     = SelectedDate;
                    trans.Commit();
                    row.SetTag(Resource.String.RouteItemUUID, newRouteItem.UUID);
                }
                row.SetTag(Resource.String.PharmacyUUID, item.UUID);

                row.FindViewById <TextView>(Resource.Id.riPharmacyTV).Text = item.Name;
                row.SetTag(Resource.String.RouteItemOrder, RouteTable.ChildCount);
                row.FindViewById <TextView>(Resource.Id.riOrderTV).Text = (RouteTable.ChildCount + 1).ToString();

                row.FindViewById <ImageView>(Resource.Id.riDeleteIV).Click += RowDelete_Click;
                row.LongClick += Row_LongClick;
                row.Drag      += Row_Drag;

                RouteTable.AddView(row);
            };

            RouteSearchItemsSource = new List <RouteSearchItem>();
            var pharmacies = MainDatabase.GetItems <Pharmacy>();

            foreach (var item in pharmacies)
            {
                RouteSearchItemsSource.Add(
                    new RouteSearchItem(
                        item.UUID,
                        string.IsNullOrEmpty(item.GetName()) ? string.Empty : item.GetName(),
                        string.IsNullOrEmpty(item.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(item.Subway).name,
                        string.IsNullOrEmpty(item.Region) ? string.Empty : MainDatabase.GetItem <Region>(item.Region).name,
                        string.IsNullOrEmpty(item.Brand) ? string.Empty : item.Brand,
                        string.IsNullOrEmpty(item.Address) ? string.Empty : item.Address
                        )
                    );
            }
            SearchedItems  = new List <RouteSearchItem>();
            SearchSwitcher = FindViewById <ViewSwitcher>(Resource.Id.raSearchVS);
            SearchSwitcher.SetInAnimation(this, Android.Resource.Animation.SlideInLeft);
            SearchSwitcher.SetOutAnimation(this, Android.Resource.Animation.SlideOutRight);

            SearchImage        = FindViewById <ImageView>(Resource.Id.raSearchIV);
            SearchImage.Click += (sender, e) => {
                if (CurrentFocus != null)
                {
                    var imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(CurrentFocus.WindowToken, HideSoftInputFlags.None);
                }

                SearchSwitcher.ShowNext();
            };

            SearchEditor = FindViewById <EditText>(Resource.Id.raSearchET);

            SearchEditor.AfterTextChanged += (sender, e) => {
                var text = e.Editable.ToString();

                if (string.IsNullOrEmpty(text))
                {
                    foreach (var item in RouteSearchItems)
                    {
                        item.Match = string.Empty;
                    }
                    PharmacyTable.Adapter = new RoutePharmacyAdapter(this, RouteSearchItems);
                    return;
                }

                var w = new SDiag.Stopwatch();
                w.Start();
                SearchedItems = new List <RouteSearchItem>();
                var matchFormat = @"Совпадение: {0}";
                var culture     = CultureInfo.GetCultureInfo("ru-RU");
                // 2 поиск
                foreach (var item in RouteSearchItems)
                {
                    if (item.IsVisible)
                    {
                        //item.Subway = null;
                        if (culture.CompareInfo.IndexOf(item.Subway, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"метро=" + item.Subway);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Region, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"район=" + item.Region);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Brand, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"бренд=" + item.Brand);
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }

                        if (culture.CompareInfo.IndexOf(item.Address, text, CompareOptions.IgnoreCase) >= 0)
                        {
                            item.Match = string.Format(matchFormat, @"адрес");
                            SearchedItems.Add(item);
                            //if (SearchedItems.Count > C_ITEMS_IN_RESULT) break;
                            continue;
                        }
                    }
                }
                w.Stop();
                SDiag.Debug.WriteLine(@"Search: поиск={0}", w.ElapsedMilliseconds);

                PharmacyTable.Adapter = new RoutePharmacyAdapter(this, SearchedItems);
            };

            RouteTable = FindViewById <LinearLayout>(Resource.Id.raRouteTable);

            FindViewById <Button>(Resource.Id.raSelectDateB).Click += (sender, e) => {
                DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime date) {
                    SDiag.Debug.WriteLine("DatePicker:{0}", date.ToLongDateString());
                    SDiag.Debug.WriteLine("DatePicker:{0}", new DateTimeOffset(date));
                    SelectedDate = new DateTimeOffset(date, new TimeSpan(0, 0, 0));;
                    RefreshTables();
                });
                frag.Show(FragmentManager, DatePickerFragment.TAG);
            };

            Info      = FindViewById <TextView>(Resource.Id.raInfoTV);
            Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);

            var switcher = FindViewById <ViewSwitcher>(Resource.Id.raSwitchViewVS);

            FindViewById <ImageView>(Resource.Id.raSwitchIV).Click += (sender, e) => {
                SDiag.Debug.WriteLine(@"switcher:{0}; Resource{1}", switcher.CurrentView.Id, Resource.Id.raContainerVP);
                if (switcher.CurrentView.Id != Resource.Id.raContainerVP)
                {
                    Info.Text = string.Format(
                        @"Период планирования: {0} недели ({1} дней). Номер недели: {2}",
                        Helper.WeeksInRoute, Helper.WeeksInRoute * 5, 1
                        );
                    var pager = FindViewById <ViewPager>(Resource.Id.raContainerVP);
                    pager.AddOnPageChangeListener(this);
                    pager.Adapter = new RoutePagerAdapter(SupportFragmentManager);
                }
                else
                {
                    Info.Text = string.Format(@"Период планирования: {0} недели ({1} дней)", Helper.WeeksInRoute, Helper.WeeksInRoute * 5);
                }
                switcher.ShowNext();
            };
        }
        void GenerateData_Click(object sender, EventArgs e)
        {
            var rnd = new Random();

            var step        = 7;
            var visitsCount = 10;
            var baseDate    = DateTimeOffset.Now.AddDays(-1 * visitsCount * step);

            var promotions  = MainDatabase.GetItems <Promotion>();
            var drugSKUs    = MainDatabase.GetDrugSKUs();
            var pharmacies  = MainDatabase.GetItems <Pharmacy>();
            var transaction = MainDatabase.BeginTransaction();

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

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

            transaction.Commit();

            transaction = MainDatabase.BeginTransaction();

            //int count = 0;
            foreach (var pharmacy in pharmacies)
            {
                //count++;
                // Визиты
                if (true)
                {
                    for (int i = 0; i < visitsCount; i++)
                    {
                        var attendance = MainDatabase.Create <Attendance>();
                        attendance.Pharmacy = pharmacy.UUID;
                        attendance.When     = baseDate.AddDays(i * step);

                        foreach (var SKU in drugSKUs)
                        {
                            var distribution = MainDatabase.CreateData <DistributionData>(attendance.UUID);
                            distribution.DrugSKU     = SKU.uuid;
                            distribution.IsExistence = rnd.NextDouble() > 0.5;
                            distribution.Count       = rnd.Next(0, 10);
                            distribution.Price       = (int)(rnd.NextDouble() * 200);
                            distribution.IsPresence  = rnd.NextDouble() > 0.5;
                            distribution.HasPOS      = rnd.NextDouble() > 0.5;
                            distribution.Order       = @"Order " + SKU.uuid;
                            distribution.Comment     = @"Comment " + SKU.uuid;
                        }
                    }
                }

                // Продажи
                var financesCount = 5;
                baseDate = DateTimeOffset.Now.AddMonths(-3);
                for (int i = 0; i < financesCount; i++)
                {
                    foreach (var SKU in drugSKUs)
                    {
                        var financeData = MainDatabase.Create <FinanceData>();
                        financeData.Pharmacy = pharmacy.UUID;
                        financeData.Period   = baseDate.AddMonths(i);
                        financeData.DrugSKU  = SKU.uuid;
                        financeData.Sale     = rnd.NextDouble() > 0.3 ? null : (float?)(rnd.NextDouble() * 20);
                        financeData.Purchase = rnd.NextDouble() > 0.4 ? null : (float?)(rnd.NextDouble() * 20);
                        financeData.Remain   = rnd.NextDouble() > 0.5 ? null : (float?)(rnd.NextDouble() * 20);
                    }
                }

                // Содержание визите = Презентаци
                int employeesCount = 3;
                //int presentationsCount = 5;
                var attendanceLast = MainDatabase.GetAttendaces(pharmacy.UUID).OrderByDescending(i => i.When).FirstOrDefault();
                var positions      = MainDatabase.GetItems <Position>();
                var workTypes      = MainDatabase.GetItems <WorkType>();
                var brands         = MainDatabase.GetItems <DrugBrand>();
                var employees      = MainDatabase.GetEmployees(pharmacy.UUID);

                if (employees.Count == 0)
                {
                    for (int emp = 0; emp < employeesCount; emp++)
                    {
                        var employee = MainDatabase.CreateEmployee(pharmacy.UUID);
                        employee.SetSex(Sex.Male);
                        employee.Name = (rnd.NextDouble() > 0.5 ? @"Иванов" : @"Петров") + @" "
                                        + (rnd.NextDouble() > 0.5 ? @"Иван" : @"Петр") + @" "
                                        + (rnd.NextDouble() > 0.5 ? @"Иванович" : @"Петрович");
                        employee.Position  = positions[rnd.Next(positions.Count)].uuid;
                        employee.BirthDate = DateTimeOffset.Now.AddYears(-rnd.Next(25, 40)).AddDays((rnd.NextDouble() - 0.5) * 365);
                        employees.Add(employee);
                    }
                }

                foreach (var employee in employees)
                {
                    foreach (var brand in brands)
                    {
                        if (rnd.NextDouble() > 0.5)
                        {
                            continue;
                        }

                        for (int wt = 0; wt < workTypes.Count; wt++)
                        {
                            if (rnd.NextDouble() > 0.5)
                            {
                                continue;
                            }

                            var presentationData = MainDatabase.CreateData <PresentationData>(attendanceLast.UUID);
                            presentationData.Employee = employee.UUID;
                            presentationData.Brand    = brand.uuid;
                            presentationData.WorkType = workTypes[wt].uuid;
                        }
                    }
                }

                // Содержание визите = Фарм-кружок
                foreach (var employee in employees)
                {
                    if (rnd.NextDouble() > 0.5)
                    {
                        continue;
                    }

                    foreach (var brand in brands)
                    {
                        if (rnd.NextDouble() > 0.5)
                        {
                            continue;
                        }

                        var coterieData = MainDatabase.CreateData <CoterieData>(attendanceLast.UUID);
                        coterieData.Employee = employee.UUID;
                        coterieData.Brand    = brand.uuid;
                    }
                }

                // Акция
                var promotionData = MainDatabase.CreateData <PromotionData>(attendanceLast.UUID);
                promotionData.Promotion = promotions[rnd.Next(promotions.Count - 1)].uuid;
                promotionData.Text      = @"promotionData";

                // Активность конкурентов
                var competitorData = MainDatabase.CreateData <CompetitorData>(attendanceLast.UUID);
                competitorData.Text = @"competitorData";

                // Сообщения от аптеки
                var messageTypes = MainDatabase.GetItems <MessageType>();
                foreach (var item in messageTypes)
                {
                    if (rnd.NextDouble() > 0.5)
                    {
                        continue;
                    }

                    var messageData = MainDatabase.CreateData <MessageData>(attendanceLast.UUID);
                    messageData.Type = item.uuid;
                    messageData.Text = @"messageData " + item.uuid;
                }

                // Резюме визита;
                var resumeData = MainDatabase.CreateData <ResumeData>(attendanceLast.UUID);
                resumeData.Text = @"resumeData";
            }

            transaction.Commit();

            RefreshView();
        }
Esempio n. 10
0
        void UploadPhoto_Click(object sender, EventArgs e)
        {
            if (CancelSource != null && CancelToken.CanBeCanceled)
            {
                CancelSource.Cancel();
            }
            if (CSForLibraryFiles != null && CTForLibraryFiles.CanBeCanceled)
            {
                CSForLibraryFiles.Cancel();
            }
            var progress = ProgressDialog.Show(this, string.Empty, @"Выгрузка фото");

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

                MainDatabase.Username = USERNAME;

                var client = new RestClient(HOST_URL);
                IRestRequest request;
                IRestResponse response;
                //var client = new RestClient("http://sbl-crm-project-pafik13.c9users.io:8080/");

                using (var trans = MainDatabase.BeginTransaction()) {
                    foreach (var photo in MainDatabase.GetItemsToSync <PhotoData>())
                    {
                        try {
                            //Toast.MakeText(this, string.Format(@"Загрузка фото с uuid {0} по посещению с uuid:{1}", photo.UUID, photo.Attendance), ToastLength.Short).Show();
                            SDiag.Debug.WriteLine(string.Format(@"Загрузка фото с uuid {0} по посещению с uuid:{1}", photo.UUID, photo.Attendance));

                            request = new RestRequest(@"PhotoData/upload", Method.POST);
                            request.AddQueryParameter(@"access_token", ACCESS_TOKEN);
                            //request.AddQueryParameter(@"Stamp", photo.Stamp.ToString());
                            request.AddQueryParameter(@"Attendance", photo.Attendance);
                            request.AddQueryParameter(@"PhotoType", photo.PhotoType);
                            request.AddQueryParameter(@"Brand", photo.Brand);
                            request.AddQueryParameter(@"Latitude", photo.Latitude.ToString(CultureInfo.CreateSpecificCulture(@"en-GB")));
                            request.AddQueryParameter(@"Longitude", photo.Longitude.ToString(CultureInfo.CreateSpecificCulture(@"en-GB")));
                            request.AddFile(@"photo", File.ReadAllBytes(photo.PhotoPath), Path.GetFileName(photo.PhotoPath), string.Empty);

                            response = client.Execute(request);

                            switch (response.StatusCode)
                            {
                            case HttpStatusCode.OK:
                            case HttpStatusCode.Created:
                                // TODO: переделать на вызов с проверкой открытой транзакции
                                photo.IsSynced = true;
                                if (!photo.IsManaged)
                                {
                                    MainDatabase.SavePhoto(photo);
                                }
                                //Toast.MakeText(this, "Фото ЗАГРУЖЕНО!", ToastLength.Short).Show();
                                SDiag.Debug.WriteLine("Фото ЗАГРУЖЕНО!");
                                continue;

                            default:
                                //Toast.MakeText(this, "Не удалось загрузить фото по посещению!", ToastLength.Short).Show();
                                SDiag.Debug.WriteLine("Не удалось загрузить фото по посещению!");
                                continue;
                            }
                        } catch (Exception ex) {
                            //Toast.MakeText(this, @"Error : " + ex.Message, ToastLength.Short).Show();
                            SDiag.Debug.WriteLine("Error : " + ex.Message);
                            continue;
                        }
                    }
                    trans.Commit();
                }

                MainDatabase.Dispose();
                RunOnUiThread(() => {
                    MainDatabase.Username = USERNAME;
                    // Thread.Sleep(1000);
                    progress.Dismiss();
                    RefreshView();
                });
            }).Start();
        }
Esempio n. 11
0
        public override void OnPause()
        {
            base.OnPause();
            var transaction = MainDatabase.BeginTransaction();

            Pharmacy item;

            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      = View.FindViewById <EditText>(Resource.Id.pfBrandET).Text;
            item.NumberName = View.FindViewById <EditText>(Resource.Id.pfNumberNameET).Text;
            item.LegalName  = View.FindViewById <EditText>(Resource.Id.pfLegalNameET).Text;

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

            var address = View.FindViewById <AutoCompleteTextView>(Resource.Id.pfAddressACTV);

            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 = View.FindViewById <EditText>(Resource.Id.pfPhoneET).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(View.FindViewById <EditText>(Resource.Id.pfTurnOverET).Text);
            item.Comment  = View.FindViewById <EditText>(Resource.Id.pfCommentET).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"));
            Activity.GetSharedPreferences(MainActivity.C_MAIN_PREFS, FileCreationMode.Private)
            .Edit()
            .PutString(MainActivity.C_SAVED_PHARMACY_UUID, item.UUID)
            .Commit();
        }
Esempio n. 12
0
        protected override void OnResume()
        {
            base.OnResume();

            //Start Tracking usage in this activit
            Tracking.StartUsage(this);

            var shared = GetSharedPreferences(C_MAIN_PREFS, FileCreationMode.Private);

            string username = shared.GetString(SigninDialog.C_USERNAME, string.Empty);

            if (string.IsNullOrEmpty(username))
            {
                Pharmacies            = new List <Pharmacy>();     //.Take(14).ToList();
                PharmacyTable.Adapter = new PharmacyAdapter(this, Pharmacies);

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

                var signinDialog = new SigninDialog(this);
                signinDialog.Show(fragmentTransaction, SigninDialog.TAG);
                signinDialog.SuccessSignedIn += (caller, arguments) => {
                    //Toast.MakeText(this, @"SuccessSignedIn", ToastLength.Short).Show();
                    RunOnUiThread(() => {
                        OnResume();
                        SDiag.Debug.WriteLine(@"DBPath = {0}", MainDatabase.DBPath);
                    });
                };

                SDiag.Debug.WriteLine(@"username = IsNullOrEmpty");
                return;
            }

            var ft = FragmentManager.BeginTransaction();
            var sd = FragmentManager.FindFragmentByTag(SigninDialog.TAG);

            if (sd != null)
            {
                ft.Remove(sd);
            }
            ft.Commit();

            if (!IsLocationActive() || !IsInternetActive())
            {
                return;
            }

            MainDatabase.Username = username;
            Helper.Username       = username;

            var agentUUID = shared.GetString(SigninDialog.C_AGENT_UUID, string.Empty);

            try {
                var agent = MainDatabase.GetItem <Agent>(agentUUID);
                MainDatabase.AgentUUID = agent.uuid;
                Helper.WeeksInRoute    = agent.weeksInRout;
                Helper.WorkMode        = agent.GetWorkMode();
                Helper.AndroidId       = Helper.GetAndroidId(this);
            } catch (Exception ex) {
                SDiag.Debug.WriteLine(ex.Message);
            }


            var packageInfo = ApplicationContext.PackageManager.GetPackageInfo(ApplicationContext.PackageName, 0);
            var version     = string.Format("Версия: {0} ({1})", packageInfo.VersionName, packageInfo.VersionCode);

            FindViewById <TextView>(Resource.Id.maVersionTV).Text = version;

            var w = new SDiag.Stopwatch();

            w.Restart();
            var currentRouteItems = MainDatabase.GetRouteItems(DateTimeOffset.Now);

            if (currentRouteItems.Count() > 0)
            {
                var nextDate      = DateTimeOffset.Now.AddDays(Helper.WeeksInRoute * 7);
                var date          = new DateTimeOffset(nextDate.Year, nextDate.Month, nextDate.Day, 0, 0, 0, new TimeSpan(0, 0, 0));
                var nextRoutItems = MainDatabase.GetRouteItems(date);

                if (nextRoutItems.Count() == 0)
                {
                    using (var trans = MainDatabase.BeginTransaction()){
                        foreach (var oldItem in currentRouteItems)
                        {
                            var newItem = MainDatabase.Create2 <RouteItem>();
                            newItem.Pharmacy = oldItem.Pharmacy;
                            newItem.Date     = date;
                            newItem.Order    = oldItem.Order;
                        }
                        trans.Commit();
                    }
                }
            }
            w.Stop();
            SDiag.Debug.WriteLine(@"Route: копирование={0}", w.ElapsedMilliseconds);

            w.Restart();
            int count = MainDatabase.GetItems <Attendance>()
                        .Count(att => att.When.LocalDateTime.Date == DateTimeOffset.Now.Date);

            AttendanceCount.Text = string.Format(
                @"РЕЖИМ РАБОТЫ: {0};  СЕГОДНЯ ВИЗИТОВ: {1}", Helper.GetWorkModeDesc(Helper.WorkMode), count
                );
            w.Stop();
            SDiag.Debug.WriteLine(@"OnResume: подсчет визитов={0}", w.ElapsedMilliseconds);

            var  sparseArray = SearchTable.CheckedItemPositions;
            bool hasCheckedItemInSearchTable = false;

            for (var i = 0; i < sparseArray.Size(); i++)
            {
                if (sparseArray.ValueAt(i))
                {
                    hasCheckedItemInSearchTable = true;
                    break;
                }
            }

            if (!hasCheckedItemInSearchTable)
            {
                RecreateAdapter();
            }

            var prefs = GetSharedPreferences(C_MAIN_PREFS, FileCreationMode.Private);
            var uuid  = prefs.GetString(C_SAVED_PHARMACY_UUID, string.Empty);

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

            if (SearchItems == null)
            {
                return;
            }

            if (SearchItems.ContainsKey(uuid))
            {
                w.Start();
                var pharmacy = MainDatabase.GetEntity <Pharmacy>(uuid);
                SearchItems[uuid] = new SearchItem(
                    pharmacy.UUID,
                    pharmacy.GetName(),
                    string.IsNullOrEmpty(pharmacy.Subway) ? string.Empty : MainDatabase.GetItem <Subway>(pharmacy.Subway).name,
                    string.IsNullOrEmpty(pharmacy.Region) ? string.Empty : MainDatabase.GetItem <Region>(pharmacy.Region).name,
                    string.IsNullOrEmpty(pharmacy.Brand) ? string.Empty : pharmacy.Brand
                    );
            }
            prefs.Edit().PutString(C_SAVED_PHARMACY_UUID, string.Empty).Commit();
            w.Stop();
            SDiag.Debug.WriteLine(@"Search: обновление={0}", w.ElapsedMilliseconds);
        }