Example #1
0
        /// <summary>
        /// Saves a model
        /// </summary>
        /// <param name="connTran">Transaction object</param>
        /// <param name="model">The model</param>
        /// <returns>The saved model</returns>
        /// <exception cref="TimeoutException">Throws a TimeoutException if call doesn't complete within specified time duration</exception>
        /// <exception cref="NotSavedException">Throws a NotSavedException if saving fails for any reason</exception>
        /// <remarks>This method is called by the SaveAsync(T model) overload. Calling it directly is unsafe as save data and sync
        /// information will not be wrapped in a transaction which may introduce inconsistencies in data</remarks>
        public virtual async Task <SaveResponse <T> > SaveAsync(SQLiteConnection connTran, T model)
        {
            if (connTran == null)
            {
                return(null);
            }

            await DataAccess.Instance.SaveAsync(model);

            var obj = model as SynchronizableModelBase;

            if (obj != null && typeof(T) != typeof(SyncRecord))
            {
                SyncingController syncingController = new SyncingController();
                return(new SaveResponse <T>(model, await syncingController.SynchronizeOrQueue(connTran, obj)));
            }

            return(new SaveResponse <T>(model, default(PostResponse)));
        }
Example #2
0
        /// <summary>
        /// Saves customer status and if necessary the related product.
        /// If the status details for the product already exist, they are deleted
        /// </summary>
        /// <param name="status">The status as supplied by the server</param>
        /// <param name="customer">The customer</param>
        /// <param name="connTran">The connection object for wrapping db calls in a transaction</param>
        /// <returns>A list of all saved items or null if the status was null</returns>
        /// <exception cref="NotSavedException">NotSavedException is thrown if even one item could not be saved</exception>
        public async Task <List <CustomerRegistrationStepsStatus> > SaveAsync(SQLiteConnection connTran, CustomerStatus status, Customer customer)
        {
            if (status == null || status.CustomerNotFound.IsBlank() == false)
            {
                return(null);
            }

            if (status.CustomerProduct.IsBlank())
            {
                status.CustomerProduct = "Product III";
            }

            CriteriaBuilder criteriaBuilder = new CriteriaBuilder();

            criteriaBuilder.Add("DisplayName", status.CustomerProduct);

            string         query    = this.ProductsController.QueryBuilder(criteriaBuilder);
            List <Product> products = await this.ProductsController.SelectQueryAsync(query);

            Product product = null;

            if (products != null)
            {
                product = products.OrderByDescending(prod => prod.Modified).FirstOrDefault();
            }

            List <CustomerRegistrationStepsStatus> resultList = new List <CustomerRegistrationStepsStatus>();

            if (product == null)
            {
                product = new Product
                {
                    DisplayName = status.CustomerProduct
                };

                await this.ProductsController.SaveAsync(connTran, product);
            }
            else
            {
                string sql =
                    string.Format(
                        "Delete from CustomerRegistrationStepsStatus where ProductId='{0}' and CustomerId='{1}'",
                        product.Id, customer.Id);
                await DataAccess.Instance.RunQueryAsync(sql);
            }

            if (status.Steps != null)
            {
                foreach (var step in status.Steps)
                {
                    CustomerRegistrationStepsStatus registrationStepsStatus = new CustomerRegistrationStepsStatus
                    {
                        CustomerId     = customer.Id,
                        ProductId      = product.Id,
                        RequestStatus  = status.RequestStatus,
                        StepName       = step.StepName,
                        StepNumber     = step.StepNumber,
                        StepStatus     = step.StepStatus,
                        AdditionalInfo = status.AdditionalInfo
                    };

                    var saveResponse = await base.SaveAsync(connTran, registrationStepsStatus);

                    if (saveResponse.SavedModel != null)
                    {
                        resultList.Add(saveResponse.SavedModel);
                    }
                    else
                    {
                        throw new NotSavedException();
                    }
                }
            }

            SyncingController syncingController = new SyncingController();
            SyncRecord        syncRecord        = await syncingController.GetSyncRecordAsync(customer.RequestId);

            if (syncRecord != null)
            {
                syncRecord.Status = RecordStatus.Synced;
                await syncingController.SaveAsync(connTran, syncRecord);
            }

            return(resultList);
        }
Example #3
0
        public async Task <Customer> SaveCustomerToDevice(
            Customer personRegistrationInfo,
            CustomerRegistrationCompletedEventArgs e, bool b)
        {
            ProspectsController prospectsController = new ProspectsController();

            try
            {
                Prospect prospect = await prospectsController
                                    .GetByPhoneNumberAsync(personRegistrationInfo.Phone, false);

                this.Logger.Debug("Trying to save customer");

                // check whether the customer is on the device, if not save the customer
                Customer existingCustomer =
                    await this.GetSingleRecord(new CriteriaBuilder().Add("Phone", personRegistrationInfo.Phone));

                if (existingCustomer != null)
                {
                    personRegistrationInfo.Id = existingCustomer.Id;
                }

                await DataAccess.Instance.Connection.RunInTransactionAsync(
                    async connTran =>
                {
                    DataAccess.Instance.StartTransaction(connTran);
                    await this.SaveAsync(connTran, personRegistrationInfo);
                    if (personRegistrationInfo.Id != default(Guid))
                    {
                        await
                        new CustomerProductController().SaveCustomerProductToDevice(
                            connTran,
                            personRegistrationInfo.Id,
                            personRegistrationInfo.Product);

                        if (prospect != null)
                        {
                            this.Logger.Debug("There was a prospect with the same number so we convert to customer");
                            prospect.Converted = true;
                            await prospectsController.SaveAsync(connTran, prospect);
                        }

                        RecordStatus syncStatus = RecordStatus.Synced;

                        if (personRegistrationInfo.Channel == DataChannel.Fallback)
                        {
                            if (e.Succeeded)
                            {
                                syncStatus = RecordStatus.FallbackSent;
                                this.Logger.Debug("Status = " + syncStatus);
                            }
                            else
                            {
                                syncStatus = RecordStatus.Pending;
                                this.Logger.Debug("Status = " + syncStatus);
                            }
                        }

                        SyncingController syncController = new SyncingController();

                        SyncRecord syncRec = await syncController.GetSyncRecordAsync(personRegistrationInfo.RequestId);
                        this.Logger.Debug("Fetching sync record for customer");

                        if (syncRec == null)
                        {
                            this.Logger.Debug("The sync record is null so we generate one");
                            syncRec = new SyncRecord
                            {
                                ModelId   = personRegistrationInfo.Id,
                                ModelType = personRegistrationInfo.TableName,
                                Status    = syncStatus,
                                RequestId = personRegistrationInfo.RequestId
                            };
                        }
                        else
                        {
                            syncRec.Status = syncStatus;
                        }

                        await syncController.SaveAsync(connTran, syncRec);
                    }
                });

                DataAccess.Instance.CommitTransaction();
                return(personRegistrationInfo);
            }
            catch (DuplicateValuesException ex)
            {
                throw new DuplicateValuesException(ex.FieldName, ex.Value, ex.Count);
            }
            catch (Exception exception)
            {
                this.Logger.Error(exception);
                return(null);
            }
        }
        /// <summary>
        /// Called to save a customer to the device
        /// </summary>
        /// <param name="e">The event arguments</param>
        /// <param name="smsSendAttempts">Number of attempts</param>
        /// <param name="smsAttemptLimit">The Limit</param>
        /// <returns>An empty task</returns>
        private async Task SaveCustomerToDevice(CustomerService.RegistrationStatusChangedEventArgs e, int smsSendAttempts, int smsAttemptLimit)
        {
            bool succeeded = e.SmsRegistrationSucceeded || e.Response.RegistrationSuccessful;

            if (!succeeded)
            {
                this.Logger.Debug(string.Format("Sms send attempts = {0} and sms send limts = {1}", smsSendAttempts, smsAttemptLimit));

                succeeded = e.Channel == DataChannel.Fallback && smsAttemptLimit == smsSendAttempts;
                if (!succeeded)
                {
                    return;
                }
            }

            this.Logger.Debug("Attempting to save customer to device");
            if (e.Response == null || e.Response.Customer == null)
            {
                return;
            }

            ProspectsController prospectsController = new ProspectsController();

            Mkopa.Core.BL.Models.People.Prospect prospect = await prospectsController
                                                            .GetByPhoneNumberAsync(e.Response.Customer.Phone);

            await Resolver.Instance.Get <ISQLiteDB>().Connection.RunInTransactionAsync(
                async(SQLiteConnection connTran) =>
            {
                try
                {
                    this.Logger.Debug("Trying to save customer");
                    CustomersController customersController = new CustomersController();
                    e.Response.Customer.Channel             = e.Channel;
                    string customerPhone = e.Response.Customer.Phone;
                    Guid custGuid;

                    Mkopa.Core.BL.Models.People.Customer customer =
                        await customersController.GetSingleByCriteria(CriteriaBuilder.New()
                                                                      .Add("Phone", customerPhone));

                    // customer to have more than one product
                    if (customer == null || customer.Id == default(Guid))
                    {
                        SaveResponse <Mkopa.Core.BL.Models.People.Customer> saveResponse =
                            await customersController.SaveAsync(connTran, e.Response.Customer, true);

                        if (saveResponse.SavedModel == null || saveResponse.SavedModel.Id == default(Guid))
                        {
                            new ReusableScreens(this.Activity)
                            .ShowInfo(
                                Resource.String.customer_save_err_actionbar,
                                Resource.String.customer_save_err_title,
                                Resource.String.customer_save_err_message,
                                Resource.String.customer_save_err_button);
                            return;
                        }
                        custGuid = saveResponse.SavedModel.Id;
                    }
                    else
                    {
                        custGuid = customer.Id;
                    }

                    await this.SaveCustomerProductToDevice(custGuid, connTran);

                    if (prospect != null)
                    {
                        this.Logger.Debug("There was a prospect with the same number so we convert to customer");
                        prospect.Converted = true;
                        await prospectsController.SaveAsync(connTran, prospect);
                    }

                    RecordStatus syncStatus = e.Channel == DataChannel.Fallback
                                ? (e.SmsRegistrationSucceeded
                                    ? RecordStatus.FallbackSent
                                    : RecordStatus.Pending)
                                : RecordStatus.Synced;

                    SyncingController syncController = new SyncingController();

                    SyncRecord syncRec = await syncController.GetSyncRecordAsync(e.Response.Customer.RequestId);
                    this.Logger.Debug("Fetching sync record for customer");

                    if (syncRec == null)
                    {
                        this.Logger.Debug("The sync record is null so we generate one");
                        syncRec = new SyncRecord
                        {
                            ModelId   = e.Response.Customer.Id,
                            ModelType = e.Response.Customer.TableName,
                            Status    = syncStatus,
                            RequestId = e.Response.Customer.RequestId
                        };
                        this.Logger.Debug("Saving generated sync record");
                        SaveResponse <SyncRecord> syncSaveResponse = await syncController.SaveAsync(
                            connTran,
                            syncRec);

                        this.Logger.Debug("Sync record was saved correctly");
                    }
                    else
                    {
                        syncRec.Status = syncStatus;
                    }

                    await syncController.SaveAsync(connTran, syncRec);
                }
                catch (Exception exception)
                {
                    this.Logger.Error(exception);
                }
            });
        }