Example #1
0
        public List <CustomerCategory> GetCustomerCategories(string buildPath)
        {
            bool isRental = buildPath.ToUpper().StartsWith("RENTAL");

            string qry = "select  CCCode,CCDesc from [DataSet].CustomerCategories";

            if (isRental)
            {
                qry = qry + " where CCCode > 100 or CCCode = 0 ";
            }
            qry = qry + " Order by CCCode";
            qry = PervasiveSqlUtilities.SetDataSource(qry, buildPath);
            try
            {
                List <CustomerCategory> result = new List <CustomerCategory>();

                var data = PervasiveSqlUtilities.FetchPervasiveData(qry);
                foreach (DataRow row in data.Rows)
                {
                    CustomerCategory c = new CustomerCategory(row);
                    result.Add(c);
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " -> [" + qry + "]");
            }
        }
        public bool CheckCustomerCategoryNameExist(CustomerCategory customerCategory)
        {
            try
            {
                using (SqlConnection con = _databaseFactory.GetDBConnection())
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        cmd.Connection  = con;
                        cmd.CommandText = "[PSA].[CheckCustomerCategoryNameExist]";
                        cmd.Parameters.Add("@Code", SqlDbType.Int).Value          = customerCategory.Code;
                        cmd.Parameters.Add("@Name", SqlDbType.NVarChar, -1).Value = customerCategory.Name;
                        cmd.CommandType = CommandType.StoredProcedure;
                        Object res = cmd.ExecuteScalar();
                        return(res.ToString() == "Exists" ? true : false);
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ActionResult Delete(CustomerCategory model)
        {
            int result = new CustomerCategoryRepository().DeleteCustomerCategory(model);

            if (result == 0)
            {
                TempData["Success"]          = "Deleted Successfully!";
                TempData["CusCategoryRefNo"] = model.CusCategoryRefNo;
                return(RedirectToAction("Create"));
            }
            else
            {
                if (result == 1)
                {
                    TempData["error"]            = "Sorry!! You Cannot Delete This Customer Category It Is Already In Use";
                    TempData["CusCategoryRefNo"] = null;
                }
                else
                {
                    TempData["error"]            = "Oops!!..Something Went Wrong!!";
                    TempData["CusCategoryRefNo"] = null;
                }
                return(RedirectToAction("Create"));
            }
        }
        /// <summary>
        /// Get a list of QueryFilter that represent changed fields.
        /// </summary>
        /// <param name="original">Original Entity. The unchanged entity.</param>
        /// <param name="changed">Changed Entity. The entity holding the changed fields.</param>
        /// <returns>QueryFilters of CustomerCategoryProperty</returns>
        public static QueryFilters <CustomerCategoryProperty> GetChanges(CustomerCategory original, CustomerCategory changed)
        {
            // this method returns a list of changes.
            var changes = new QueryFilters <CustomerCategoryProperty>(5);

            #region Detect Changes
            if (original.CustomerCategoryID != changed.CustomerCategoryID)
            {
                changes.Add(QueryFilter.New(CustomerCategoryProperty.CustomerCategoryID, FilterConditions.Equals, changed.CustomerCategoryID));
            }
            if (string.CompareOrdinal(original.CustomerCategoryName, changed.CustomerCategoryName) != 0)
            {
                changes.Add(QueryFilter.New(CustomerCategoryProperty.CustomerCategoryName, FilterConditions.Equals, changed.CustomerCategoryName));
            }
            if (original.LastEditedBy != changed.LastEditedBy)
            {
                changes.Add(QueryFilter.New(CustomerCategoryProperty.LastEditedBy, FilterConditions.Equals, changed.LastEditedBy));
            }
            if (original.ValidFrom != changed.ValidFrom)
            {
                changes.Add(QueryFilter.New(CustomerCategoryProperty.ValidFrom, FilterConditions.Equals, changed.ValidFrom));
            }
            if (original.ValidTo != changed.ValidTo)
            {
                changes.Add(QueryFilter.New(CustomerCategoryProperty.ValidTo, FilterConditions.Equals, changed.ValidTo));
            }
            #endregion
            return(changes.Count > 0 ? changes : null);
        }
        public ActionResult Edit(CustomerCategory model)
        {
            model.OrganizationId = OrganizationId;
            model.CreatedDate    = System.DateTime.Now;
            model.CreatedBy      = UserID.ToString();

            var  repo     = new CustomerCategoryRepository();
            bool isexists = repo.IsFieldExists(repo.ConnectionString(), "CustomerCategory", "CusCategoryName", model.CusCategoryName, "CusCategoryId", model.CusCategoryId);

            if (!isexists)
            {
                var result = new CustomerCategoryRepository().UpdateCustomerCategory(model);
                if (result.CusCategoryId > 0)
                {
                    TempData["Success"]          = "Updated Successfully!";
                    TempData["CusCategoryRefNo"] = result.CusCategoryRefNo;
                    return(RedirectToAction("Create"));
                }

                else
                {
                    TempData["error"]            = "Oops!!..Something Went Wrong!!";
                    TempData["CusCategoryRefNo"] = null;
                    return(View("Create", model));
                }
            }
            else
            {
                TempData["error"]            = "This Name Alredy Exists!!";
                TempData["CusCategoryRefNo"] = null;
                return(View("Create", model));
            }
        }
        public IActionResult Index(CustomerCategory customerCategory)
        {
            int totalDiscount;
            int totalPrice = Sum(customerCategory.Customer, shoppingCart, out totalDiscount);

            return(RedirectToAction("Calculate", new { totalPrice = totalPrice, totalDiscount = totalDiscount }));
        }
 /// <summary>
 /// Compare 2 Entities for changes. NavProperties are NOT taken into account. For NavProperties use the corresponding utils for those Entities
 /// </summary>
 /// <param name="one">Entity One.</param>
 /// <param name="two">Entity Two.</param>
 /// <returns>True if there is changes. False if no changes found.</returns>
 public static bool HasChanges(CustomerCategory one, CustomerCategory two)
 {
     // this method returns true if differences are found between the 2 entities.
     #region Detect Changes
     if (one.CustomerCategoryID != two.CustomerCategoryID)
     {
         return(true);
     }
     if (string.CompareOrdinal(one.CustomerCategoryName, two.CustomerCategoryName) != 0)
     {
         return(true);
     }
     if (one.LastEditedBy != two.LastEditedBy)
     {
         return(true);
     }
     if (one.ValidFrom != two.ValidFrom)
     {
         return(true);
     }
     if (one.ValidTo != two.ValidTo)
     {
         return(true);
     }
     #endregion
     return(false);
 }
Example #8
0
        public CustomerCategory InsertCustomerCategory(CustomerCategory objCustomerCategory)
        {
            using (IDbConnection connection = OpenConnection(dataConnection))

            {
                var result = new CustomerCategory();

                IDbTransaction trn = connection.BeginTransaction();

                string sql = @"INSERT INTO CustomerCategory(CusCategoryRefNo,CusCategoryName,CusCategoryShortName,CreatedBy,CreatedDate,OrganizationId) 
                                VALUES(@CusCategoryRefNo,@CusCategoryName,@CusCategoryShortName,@CreatedBy,getDate(),@OrganizationId);
                                SELECT CAST(SCOPE_IDENTITY() as int)";

                try
                {
                    int internalid = DatabaseCommonRepository.GetInternalIDFromDatabase(connection, trn, typeof(CustomerCategory).Name, "0", 1);
                    objCustomerCategory.CusCategoryRefNo = "CUSCAT/" + internalid;

                    int id = connection.Query <int>(sql, objCustomerCategory, trn).Single();
                    objCustomerCategory.CusCategoryId = id;
                    InsertLoginHistory(dataConnection, objCustomerCategory.CreatedBy, "Create", "Customer Category", id.ToString(), "0");
                    //connection.Dispose();
                    trn.Commit();
                }
                catch (Exception ex)
                {
                    trn.Rollback();
                    objCustomerCategory.CusCategoryId    = 0;
                    objCustomerCategory.CusCategoryRefNo = null;
                }
                return(objCustomerCategory);
            }
        }
Example #9
0
        public async Task <IHttpActionResult> Post(CustomerCategory item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            item.ObjectState = ObjectState.Added;
            _service.Insert(item);

            try
            {
                await _unitOfWorkAsync.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ItemExists(item.CustomerCategoryID))
                {
                    return(Conflict());
                }
                throw;
            }

            return(Created(item));
        }
Example #10
0
 public CustomerCategory Put(CustomerCategory item)
 {
     try
     {
         var identity = User.Identity as ClaimsIdentity;
         int compid = 0, userid = 0;
         foreach (Claim claim in identity.Claims)
         {
             if (claim.Type == "compid")
             {
                 compid = int.Parse(claim.Value);
             }
             if (claim.Type == "userid")
             {
                 userid = int.Parse(claim.Value);
             }
         }
         logger.Info("User ID : {0} , Company Id : {1}", compid, userid);
         return(context.PutCustomerCategory(item));
     }
     catch
     {
         return(null);
     }
 }
Example #11
0
        public int DeleteCustomerCategory(CustomerCategory objCustomerCategory)
        {
            int result = 0;

            using (IDbConnection connection = OpenConnection(dataConnection))
            {
                string sql = @" Update CustomerCategory Set isActive=0 WHERE CusCategoryId=@CusCategoryId";
                try
                {
                    var id = connection.Execute(sql, objCustomerCategory);
                    objCustomerCategory.CusCategoryId = id;
                    InsertLoginHistory(dataConnection, objCustomerCategory.CreatedBy, "Delete", "Customer Category", id.ToString(), "0");
                    result = 0;
                }
                catch (SqlException ex)
                {
                    int err = ex.Errors.Count;
                    if (ex.Errors.Count > 0)  // Assume the interesting stuff is in the first error
                    {
                        switch (ex.Errors[0].Number)
                        {
                        case 547:      // Foreign Key violation
                            result = 1;
                            break;

                        default:
                            result = 2;
                            break;
                        }
                    }
                }

                return(result);
            }
        }
Example #12
0
        public override async Task <CustomerDto> Update(CustomerUpdateDto input)
        {
            //var output = await base.Update(input);
            //return output;

            CheckUpdatePermission();
            var entity = await GetEntityByIdAsync(input.Id);

            MapToEntity(input, entity);

            #region Customer Category Setting
            // Assemble category.
            entity.CustomerCategorySettings = new List <CustomerCategorySetting>();

            // 1. Get old category.
            List <CustomerCategorySetting> settings
                = customerCategorySettingRepository.GetAll()
                  .Where(t => t.CustomerId == input.Id)
                  .ToList();

            // Get the category from database that had already existed.
            foreach (var item in settings)
            {
                if (input.CategorySettings.Contains(item.CategoryCode))
                {
                    // this category still alive. and ignore it for add.
                    input.CategorySettings.Remove(item.CategoryCode);
                }
                else
                {
                    // remove from local list object.
                    // xx settings.Remove(item);
                    // remove from database.
                    customerCategorySettingRepository.Delete(item.Id);
                }
            }

            // Get the surplus category from input, that need to be added in database.
            foreach (var code in input.CategorySettings)
            {
                CustomerCategory category
                    = customerCategoryRepository.FirstOrDefault(t => t.Code == code);

                customerCategorySettingRepository.Insert(new CustomerCategorySetting {
                    CustomerCategoryId = category.Id,
                    CustomerId         = entity.Id,
                    TenantId           = this.AbpSession.TenantId,
                    CreatorUserId      = this.AbpSession.UserId,
                    IsActive           = true,
                    Status             = 0
                });
            }

            #endregion

            await CurrentUnitOfWork.SaveChangesAsync();

            return(MapToEntityDto(entity));
        }
        public ActionResult Create()
        {
            ViewBag.Title = "Create";
            CustomerCategory CustomerCategory = new CustomerCategory();

            CustomerCategory.CusCategoryRefNo = new CustomerCategoryRepository().GetRefNo(CustomerCategory);
            return(View(CustomerCategory));
        }
Example #14
0
 public CustomerCategory CreateCustomerCategory(CustomerCategory category)
 {
     if (!GetiItemCategories().Any(i => i.Name.Equals(category.Name)))
     {
         return(customerCategories.Insert(category));
     }
     return(null);
 }
Example #15
0
        public JsonResult SaveModel(CustomerCategoryForm form)
        {
            SaveReturn saveReturn = new SaveReturn();

            if (form == null)
            {
                saveReturn.Messages.Add(new SaveMessage(SaveMessageType.Error,
                                                        SaveMessageDelivery.MessageLine,
                                                        "Data error, value is null"));
            }

            if (!saveReturn.HasErrors)
            {
                CustomerCategory cc;

                if (form.CustomerCategoryId == 0)
                { // new category
                    cc = new CustomerCategory();
                    BindFormToDbModel(form, cc, saveReturn);
                    if (!saveReturn.HasErrors)
                    {
                        db.CustomerCategorys.Add(cc);
                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            if (IsDuplicateKey(ex))
                            {
                                saveReturn.Messages.Add(new SaveMessage(SaveMessageType.Error,
                                                                        SaveMessageDelivery.MessageLine,
                                                                        "Duplicate Customer Category Description"));
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }
                else
                { // existing
                    cc = db.CustomerCategorys.Where(r => r.CustomerCategoryId == form.CustomerCategoryId).SingleOrDefault();
                    BindFormToDbModel(form, cc, saveReturn);
                    if (!saveReturn.HasErrors)
                    {
                        db.SaveChanges();
                    }
                }
                if (!saveReturn.HasErrors)
                {
                    saveReturn.Model = cc; // model to re-display
                }
            }
            return(Json(saveReturn));
        }
Example #16
0
        // PUT: api/CustomerCategory/5
        public IHttpActionResult Put([FromBody] CustomerCategory category)
        {
            var returnCategory = service.UpdatecCustomerCategory(category);

            if (returnCategory == null)
            {
                return(BadRequest("Category not found."));
            }
            return(Ok(returnCategory));
        }
Example #17
0
        // POST: api/CustomerCategory
        public IHttpActionResult Post([FromBody] CustomerCategory category)
        {
            var returnCategory = service.CreateCustomerCategory(category);

            if (returnCategory == null)
            {
                return(BadRequest("Category Already Exists."));
            }
            return(Ok(returnCategory));
        }
        public decimal CalculateDiscount(decimal amount, CustomerCategory customerCategory)
        {
            var discount = 0;

            if (amount > 1000)
            {
                discount = discountDb.GetDiscount(customerCategory);
            }
            return(amount * discount / 100);
        }
Example #19
0
        public decimal CalculateDiscount(decimal amount, CustomerCategory customerCategory)
        {
            var discount = 0;

            if (amount > 1000)
            {
                discount = discountDb.GetDiscount(customerCategory);
            }
            return (amount*discount/100);
        }
        public List <CustomerCategory> GetAllCustomerCategory(CustomerCategoryAdvanceSearch customerCategoryAdvanceSearch)
        {
            List <CustomerCategory> customerCategoryList = null;

            try
            {
                using (SqlConnection con = _databaseFactory.GetDBConnection())
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        cmd.Connection  = con;
                        cmd.CommandText = "[PSA].[GetAllCustomerCategory]";
                        cmd.Parameters.Add("@SearchValue", SqlDbType.NVarChar, -1).Value = string.IsNullOrEmpty(customerCategoryAdvanceSearch.SearchTerm) ? "" : customerCategoryAdvanceSearch.SearchTerm.Trim();
                        cmd.Parameters.Add("@RowStart", SqlDbType.Int).Value             = customerCategoryAdvanceSearch.DataTablePaging.Start;
                        if (customerCategoryAdvanceSearch.DataTablePaging.Length == -1)
                        {
                            cmd.Parameters.AddWithValue("@Length", DBNull.Value);
                        }
                        else
                        {
                            cmd.Parameters.Add("@Length", SqlDbType.Int).Value = customerCategoryAdvanceSearch.DataTablePaging.Length;
                        }
                        cmd.CommandType = CommandType.StoredProcedure;
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if ((sdr != null) && (sdr.HasRows))
                            {
                                customerCategoryList = new List <CustomerCategory>();
                                while (sdr.Read())
                                {
                                    CustomerCategory customerCategory = new CustomerCategory();
                                    {
                                        customerCategory.Code          = (sdr["Code"].ToString() != "" ? int.Parse(sdr["Code"].ToString()) : customerCategory.Code);
                                        customerCategory.Name          = (sdr["Name"].ToString() != "" ? sdr["Name"].ToString() : customerCategory.Name);
                                        customerCategory.TotalCount    = (sdr["TotalCount"].ToString() != "" ? int.Parse(sdr["TotalCount"].ToString()) : customerCategory.TotalCount);
                                        customerCategory.FilteredCount = (sdr["FilteredCount"].ToString() != "" ? int.Parse(sdr["FilteredCount"].ToString()) : customerCategory.FilteredCount);
                                    }
                                    customerCategoryList.Add(customerCategory);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(customerCategoryList);
        }
 /// <summary>
 /// Merge all values from one Entity into another one.
 /// </summary>
 /// <param name="source">Source Entity. Will be copied to the target.</param>
 /// <param name="target">Target Entity. Will receive the values from the source.</param>
 /// <returns>void.</returns>
 public static void Merge(CustomerCategory source, CustomerCategory target)
 {
     // this method merges 2 Entities.
     #region Merge Values
     target.CustomerCategoryID   = source.CustomerCategoryID;
     target.CustomerCategoryName = source.CustomerCategoryName;
     target.LastEditedBy         = source.LastEditedBy;
     target.ValidFrom            = source.ValidFrom;
     target.ValidTo = source.ValidTo;
     #endregion
 }
Example #22
0
        public CustomerCategory UpdateCustomerCategory(CustomerCategory objCustomerCategory)
        {
            using (IDbConnection connection = OpenConnection(dataConnection))
            {
                string sql = @"Update CustomerCategory Set CusCategoryRefNo=@CusCategoryRefNo,CusCategoryName=@CusCategoryName,CusCategoryShortName=@CusCategoryShortName OUTPUT INSERTED.CusCategoryId WHERE CusCategoryId=@CusCategoryId";

                var id = connection.Execute(sql, objCustomerCategory);
                InsertLoginHistory(dataConnection, objCustomerCategory.CreatedBy, "Update", "Customer Category", id.ToString(), "0");
                return(objCustomerCategory);
            }
        }
        public ActionResult Edit(string Id)
        {
            CustomerCategory customerCategory = context.Find(Id);

            if (customerCategory == null)
            {
                return(HttpNotFound());
            }
            else
            {
                return(View(customerCategory));
            }
        }
        public ActionResult Delete(string Id)
        {
            CustomerCategory customerCategoryToDelete = context.Find(Id);

            if (customerCategoryToDelete == null)
            {
                return(HttpNotFound());
            }
            else
            {
                return(View(customerCategoryToDelete));
            }
        }
Example #25
0
 private void removeRecord(int id)
 {
     foreach (DataGridViewRow item in gridData.Rows)
     {
         CustomerCategory dep = (CustomerCategory)item.Tag;
         if (dep.ID == id)
         {
             gridData.Rows.Remove(item);
             break;
         }
     }
     gridData.ClearSelection();
 }
Example #26
0
 private void updateRecord()
 {
     foreach (DataGridViewRow item in gridData.Rows)
     {
         CustomerCategory dep = (CustomerCategory)item.Tag;
         if (dep.ID == m_cuscat.ID)
         {
             gridData[0, item.Index].Value = m_cuscat.CODE;
             gridData[1, item.Index].Value = m_cuscat.NAME;
             break;
         }
     }
 }
        public ActionResult Create(CustomerCategory customerCategory)
        {
            if (!ModelState.IsValid)
            {
                return(View(customerCategory));
            }
            else
            {
                context.Insert(customerCategory);
                context.Commit();

                return(RedirectToAction("Index"));
            }
        }
Example #28
0
 public void ClearForm()
 {
     try
     {
         textBoxCode.Text = "";
         textBoxName.Text = "";
         m_cuscat         = new CustomerCategory();
         errorProvider1.Clear();
     }
     catch (Exception x)
     {
         KryptonMessageBox.Show(x.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
        public ActionResult ConfirmDelete(string Id)
        {
            CustomerCategory customerCategoryToDelete = context.Find(Id);

            if (customerCategoryToDelete == null)
            {
                return(HttpNotFound());
            }
            else
            {
                context.Delete(Id);
                context.Commit();
                return(RedirectToAction("Index"));
            }
        }
        public async Task <IResponse> UpdateCustomerCategoryAsync(CustomerCategory entity)
        {
            Logger?.LogInformation("'{0}' has been invoked", nameof(UpdateCustomerCategoryAsync));

            try
            {
                UnitOfWork.Repository <CustomerCategory>().Update(entity);
                await UnitOfWork.SaveChangesAsync();

                return(new Response());
            }
            catch (Exception ex)
            {
                return(new Response(Logger, nameof(UpdateCustomerCategoryAsync), ex));
            }
        }
Example #31
0
 private void gridData_SelectionChanged(object sender, EventArgs e)
 {
     if (gridData.SelectedRows.Count == 0)
     {
         return;
     }
     ClearForm();
     m_cuscat = (CustomerCategory)gridData.SelectedRows[0].Tag;
     if (m_cuscat == null)
     {
         return;
     }
     loadData();
     setEnableForm(false);
     setEditMode(EditMode.View);
 }
Example #32
0
        public int GetDiscount(CustomerCategory customerCategory)
        {
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
            {
                var command = new SqlCommand("select Percentage from Discount where CustomerCategory=@CustomerCategory", conn);

                command.Parameters.AddWithValue("CustomerCategory", customerCategory);

                conn.Open();

                object obj = command.ExecuteScalar();

                if (obj != null)
                {
                    int valor = (int) obj;
                    return valor;
                }
                throw new Exception("Value not found");
            }
        }
 public int GetDiscount(CustomerCategory customerCategory)
 {
     return 10;
 }
Example #34
0
        protected CustomerCategory CreateCustomerCategory(Customer customer, Category category)
        {
            CustomerCategory cuCa = new CustomerCategory();
            cuCa.ID = Guid.NewGuid();
            cuCa.Customer = customer;
            cuCa.Category = category;

            return cuCa;
        }