public async Task <IActionResult> Post([FromBody] FinanceLoanDocumentUIViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (vm == null || (vm.DocType != FinanceDocTypeViewModel.DocType_BorrowFrom &&
                               vm.DocType != FinanceDocTypeViewModel.DocType_LendTo))
            {
                return(BadRequest("No data is inputted"));
            }
            if (vm.HID <= 0)
            {
                return(BadRequest("Not HID inputted"));
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            // Check the items
            if (vm.Items.Count != 1)
            {
                return(BadRequest("Only one item doc is supported by far"));
            }
            if (vm.AccountVM == null || vm.AccountVM.ExtraInfo_Loan == null)
            {
                return(BadRequest("No account info!"));
            }
            if (vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs.Count <= 0)
            {
                return(BadRequest("No template docs defined!"));
            }
            else
            {
                foreach (var tdoc in vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs)
                {
                    if (!tdoc.ControlCenterID.HasValue && !tdoc.OrderID.HasValue)
                    {
                        return(BadRequest("Either control center or order shall be specified in Loan Template doc"));
                    }
                    if (tdoc.TranAmount <= 0)
                    {
                        return(BadRequest("Amount is zero!"));
                    }
                }
            }

            // Update the database
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            SqlTransaction tran        = null;
            String         queryString = "";
            Int32          nNewDocID   = -1;
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    tran = conn.BeginTransaction();

                    // First, create the doc header => nNewDocID
                    queryString = HIHDBUtility.GetFinDocHeaderInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };

                    HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vm, usrName);
                    SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam.Direction = ParameterDirection.Output;

                    Int32 nRst = await cmd.ExecuteNonQueryAsync();

                    nNewDocID = (Int32)idparam.Value;
                    cmd.Dispose();
                    cmd = null;

                    // Then, creating the items
                    foreach (FinanceDocumentItemUIViewModel ivm in vm.Items)
                    {
                        if (vm.DocType == FinanceDocTypeViewModel.DocType_BorrowFrom)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_BorrowFrom;
                        }
                        else if (vm.DocType == FinanceDocTypeViewModel.DocType_LendTo)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_LendTo;
                        }

                        queryString = HIHDBUtility.GetFinDocItemInsertString();
                        cmd         = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };
                        HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID);

                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                        cmd = null;

                        // Tags
                        if (ivm.TagTerms.Count > 0)
                        {
                            // Create tags
                            foreach (var term in ivm.TagTerms)
                            {
                                queryString = HIHDBUtility.GetTagInsertString();

                                cmd = new SqlCommand(queryString, conn, tran);

                                HIHDBUtility.BindTagInsertParameter(cmd, vm.HID, HIHTagTypeEnum.FinanceDocumentItem, nNewDocID, term, ivm.ItemID);

                                await cmd.ExecuteNonQueryAsync();

                                cmd.Dispose();
                                cmd = null;
                            }
                        }
                    }

                    // Third, go to the account creation => nNewAccountID
                    queryString = HIHDBUtility.GetFinanceAccountHeaderInsertString();

                    cmd = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };
                    HIHDBUtility.BindFinAccountInsertParameter(cmd, vm.AccountVM, usrName);

                    SqlParameter idparam2 = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam2.Direction = ParameterDirection.Output;

                    nRst = await cmd.ExecuteNonQueryAsync();

                    Int32 nNewAccountID = (Int32)idparam2.Value;
                    cmd.Dispose();
                    cmd = null;

                    // 3a. Create another item to loan document
                    var nMaxItemID = vm.Items.Max(item => item.ItemID);
                    foreach (FinanceDocumentItemUIViewModel ivm in vm.Items)
                    {
                        ivm.ItemID    = ++nMaxItemID;
                        ivm.AccountID = nNewAccountID;
                        if (vm.DocType == FinanceDocTypeViewModel.DocType_BorrowFrom)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_OpeningLiability;
                        }
                        else if (vm.DocType == FinanceDocTypeViewModel.DocType_LendTo)
                        {
                            ivm.TranType = FinanceTranTypeViewModel.TranType_OpeningAsset;
                        }

                        queryString = HIHDBUtility.GetFinDocItemInsertString();
                        SqlCommand cmd2 = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };
                        HIHDBUtility.BindFinDocItemInsertParameter(cmd2, ivm, nNewDocID);

                        await cmd2.ExecuteNonQueryAsync();

                        cmd2.Dispose();
                        cmd2 = null;
                    }

                    // Fourth, creat the Loan part
                    queryString = HIHDBUtility.GetFinanceAccountLoanInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };

                    HIHDBUtility.BindFinAccountLoanInsertParameter(cmd, vm.AccountVM.ExtraInfo_Loan, nNewDocID, nNewAccountID, usrName);
                    nRst = await cmd.ExecuteNonQueryAsync();

                    cmd.Dispose();
                    cmd = null;

                    // Fifth, create template docs
                    foreach (FinanceTmpDocLoanViewModel avm in vm.AccountVM.ExtraInfo_Loan.LoanTmpDocs)
                    {
                        queryString = HIHDBUtility.GetFinanceTmpDocLoanInsertString();

                        cmd = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };

                        HIHDBUtility.BindFinTmpDocLoanParameter(cmd, avm, nNewAccountID, usrName);
                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                        cmd = null;
                    }

                    tran.Commit();

                    // Update the buffer
                    // Account list
                    var cacheKey = String.Format(CacheKeys.FinAccountList, vm.HID, null);
                    this._cache.Remove(cacheKey);
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(exp.Message);
#endif

                if (tran != null)
                {
                    tran.Rollback();
                }

                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }
            }
            finally
            {
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            vm.ID = nNewDocID;
            var setting = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = HIHAPIConstants.DateFormatPattern,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            return(new JsonResult(vm, setting));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] FinanceAssetBuyinDocViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (vm == null || vm.accountAsset == null)
            {
                return(BadRequest("No data is inputted"));
            }

            if (vm.HID <= 0)
            {
                return(BadRequest("Not HID inputted"));
            }

            // Do basic checks
            if (String.IsNullOrEmpty(vm.TranCurr) || String.IsNullOrEmpty(vm.accountAsset.Name) ||
                (vm.IsLegacy.HasValue && vm.IsLegacy.Value && vm.Items.Count > 0) ||
                ((!vm.IsLegacy.HasValue || (vm.IsLegacy.HasValue && !vm.IsLegacy.Value)) && vm.Items.Count <= 0)
                )
            {
                return(BadRequest("Invalid input data"));
            }

            foreach (var di in vm.Items)
            {
                if (di.TranAmount == 0 || di.AccountID <= 0 || di.TranType <= 0 || (di.ControlCenterID <= 0 && di.OrderID <= 0))
                {
                    return(BadRequest("Invalid input data in items!"));
                }
            }

            String usrName = String.Empty;

            if (Startup.UnitTestMode)
            {
                usrName = UnitTestUtility.UnitTestUser;
            }
            else
            {
                var usrObj = HIHAPIUtility.GetUserClaim(this);
                usrName = usrObj.Value;
            }
            if (String.IsNullOrEmpty(usrName))
            {
                return(BadRequest("User cannot recognize"));
            }

            // Construct the Account
            var vmAccount = new FinanceAccountViewModel();

            vmAccount.HID                     = vm.HID;
            vmAccount.Name                    = vm.accountAsset.Name;
            vmAccount.Status                  = FinanceAccountStatus.Normal;
            vmAccount.CtgyID                  = FinanceAccountCtgyViewModel.AccountCategory_Asset;
            vmAccount.ExtraInfo_AS            = new FinanceAccountExtASViewModel();
            vmAccount.Owner                   = vm.AccountOwner;
            vmAccount.Comment                 = vm.accountAsset.Name;
            vmAccount.ExtraInfo_AS.Name       = vm.accountAsset.Name;
            vmAccount.ExtraInfo_AS.Comment    = vm.accountAsset.Comment;
            vmAccount.ExtraInfo_AS.CategoryID = vm.accountAsset.CategoryID;

            // Construct the Doc.
            var vmFIDoc = new FinanceDocumentUIViewModel();

            vmFIDoc.DocType  = FinanceDocTypeViewModel.DocType_AssetBuyIn;
            vmFIDoc.Desp     = vm.Desp;
            vmFIDoc.TranDate = vm.TranDate;
            vmFIDoc.HID      = vm.HID;
            vmFIDoc.TranCurr = vm.TranCurr;

            var maxItemID = 0;

            if (vm.IsLegacy.HasValue && vm.IsLegacy.Value)
            {
                // Legacy account...
            }
            else
            {
                Decimal totalAmt = 0;
                foreach (var di in vm.Items)
                {
                    if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0 ||
                        (di.ControlCenterID <= 0 && di.OrderID <= 0))
                    {
                        return(BadRequest("Invalid input data in items!"));
                    }

                    // Todo: new check the tran. type is an expense!

                    totalAmt += di.TranAmount;
                    vmFIDoc.Items.Add(di);

                    if (maxItemID < di.ItemID)
                    {
                        maxItemID = di.ItemID;
                    }
                }

                if (totalAmt != vm.TranAmount)
                {
                    return(BadRequest("Amount is not even"));
                }
            }

            var nitem = new FinanceDocumentItemUIViewModel();

            nitem.ItemID     = ++maxItemID;
            nitem.AccountID  = -1;
            nitem.TranAmount = vm.TranAmount;
            nitem.Desp       = vmFIDoc.Desp;
            nitem.TranType   = FinanceTranTypeViewModel.TranType_OpeningAsset;
            if (vm.ControlCenterID.HasValue)
            {
                nitem.ControlCenterID = vm.ControlCenterID.Value;
            }
            if (vm.OrderID.HasValue)
            {
                nitem.OrderID = vm.OrderID.Value;
            }
            vmFIDoc.Items.Add(nitem);

            // Update the database
            SqlConnection  conn        = null;
            SqlCommand     cmd         = null;
            SqlDataReader  reader      = null;
            SqlTransaction tran        = null;
            String         queryString = "";
            Int32          nNewDocID   = -1;
            String         strErrMsg   = "";
            HttpStatusCode errorCode   = HttpStatusCode.OK;

            try
            {
                // Basic check again - document level
                FinanceDocumentController.FinanceDocumentBasicCheck(vmFIDoc);

                using (conn = new SqlConnection(Startup.DBConnectionString))
                {
                    await conn.OpenAsync();

                    // Check Home assignment with current user
                    try
                    {
                        HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
                    }
                    catch (Exception)
                    {
                        errorCode = HttpStatusCode.BadRequest;
                        throw;
                    }

                    // Perfrom the doc. validation
                    await FinanceDocumentController.FinanceDocumentBasicValidationAsync(vmFIDoc, conn, -1);

                    // 0) Start the trasnaction for modifications
                    tran = conn.BeginTransaction();

                    // 1) craete the doc header => nNewDocID
                    queryString = HIHDBUtility.GetFinDocHeaderInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };

                    HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vmFIDoc, usrName);
                    SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam.Direction = ParameterDirection.Output;

                    Int32 nRst = await cmd.ExecuteNonQueryAsync();

                    nNewDocID  = (Int32)idparam.Value;
                    vmFIDoc.ID = nNewDocID;
                    cmd.Dispose();
                    cmd = null;

                    // 2), create the new account => nNewAccountID
                    queryString = HIHDBUtility.GetFinanceAccountHeaderInsertString();

                    cmd = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };
                    HIHDBUtility.BindFinAccountInsertParameter(cmd, vmAccount, usrName);
                    SqlParameter idparam2 = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
                    idparam2.Direction = ParameterDirection.Output;

                    nRst = await cmd.ExecuteNonQueryAsync();

                    vmAccount.ID = (Int32)idparam2.Value;
                    cmd.Dispose();
                    cmd = null;

                    // 3) create the Asset part of account
                    vmAccount.ExtraInfo_AS.AccountID    = vmAccount.ID;
                    vmAccount.ExtraInfo_AS.RefDocForBuy = nNewDocID;
                    queryString = HIHDBUtility.GetFinanceAccountAssetInsertString();
                    cmd         = new SqlCommand(queryString, conn)
                    {
                        Transaction = tran
                    };
                    HIHDBUtility.BindFinAccountAssetInsertParameter(cmd, vmAccount.ExtraInfo_AS);
                    nRst = await cmd.ExecuteNonQueryAsync();

                    cmd.Dispose();
                    cmd = null;

                    // 4) create the doc items
                    foreach (FinanceDocumentItemUIViewModel ivm in vmFIDoc.Items)
                    {
                        if (ivm.AccountID == -1)
                        {
                            ivm.AccountID = vmAccount.ID;
                        }

                        queryString = HIHDBUtility.GetFinDocItemInsertString();
                        cmd         = new SqlCommand(queryString, conn)
                        {
                            Transaction = tran
                        };
                        HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID);

                        await cmd.ExecuteNonQueryAsync();

                        cmd.Dispose();
                        cmd = null;

                        // Tags
                        if (ivm.TagTerms.Count > 0)
                        {
                            // Create tags
                            foreach (var term in ivm.TagTerms)
                            {
                                queryString = HIHDBUtility.GetTagInsertString();

                                cmd = new SqlCommand(queryString, conn, tran);

                                HIHDBUtility.BindTagInsertParameter(cmd, vm.HID, HIHTagTypeEnum.FinanceDocumentItem, nNewDocID, term, ivm.ItemID);

                                await cmd.ExecuteNonQueryAsync();

                                cmd.Dispose();
                                cmd = null;
                            }
                        }
                    }

                    // 5) Do the commit
                    tran.Commit();

                    // Update the buffer
                    // Account List
                    try
                    {
                        var cacheKey = String.Format(CacheKeys.FinAccountList, vm.HID, null);
                        this._cache.Remove(cacheKey);
                    }
                    catch (Exception)
                    {
                        // Do nothing here.
                    }
                    // B.S.
                    try
                    {
                        var cacheKey = String.Format(CacheKeys.FinReportBS, vm.HID);
                        this._cache.Remove(cacheKey);
                    }
                    catch (Exception)
                    {
                        // Do nothing here.
                    }
                }
            }
            catch (Exception exp)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(exp.Message);
#endif

                strErrMsg = exp.Message;
                if (errorCode == HttpStatusCode.OK)
                {
                    errorCode = HttpStatusCode.InternalServerError;
                }

                if (tran != null)
                {
                    tran.Rollback();
                }
            }
            finally
            {
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
                if (reader != null)
                {
                    reader.Dispose();
                    reader = null;
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                    cmd = null;
                }
                if (conn != null)
                {
                    conn.Dispose();
                    conn = null;
                }
            }

            if (errorCode != HttpStatusCode.OK)
            {
                switch (errorCode)
                {
                case HttpStatusCode.Unauthorized:
                    return(Unauthorized());

                case HttpStatusCode.NotFound:
                    return(NotFound());

                case HttpStatusCode.BadRequest:
                    return(BadRequest(strErrMsg));

                default:
                    return(StatusCode(500, strErrMsg));
                }
            }

            return(Ok(nNewDocID));
        }