Exemplo n.º 1
0
        public async Task Should_Error_Update_Invalid_Data()
        {
            PurchaseRequest model = await DataUtil.GetTestData("dev2");

            var responseGetById = await this.Client.GetAsync($"{URI}/{model.Id}");

            var json = await responseGetById.Content.ReadAsStringAsync();

            Dictionary <string, object> result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json.ToString());

            Assert.True(result.ContainsKey("apiVersion"));
            Assert.True(result.ContainsKey("message"));
            Assert.True(result.ContainsKey("data"));
            Assert.True(result["data"].GetType().Name.Equals("JObject"));

            PurchaseRequestViewModel viewModel = JsonConvert.DeserializeObject <PurchaseRequestViewModel>(result.GetValueOrDefault("data").ToString());

            viewModel.date     = DateTimeOffset.MinValue;
            viewModel.budget   = null;
            viewModel.unit     = null;
            viewModel.category = null;
            viewModel.items    = new List <PurchaseRequestItemViewModel> {
            };

            var response = await this.Client.PutAsync($"{URI}/{model.Id}", new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] PurchaseRequestViewModel vm)
        {
            identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;

            PurchaseRequest m = mapper.Map <PurchaseRequest>(vm);

            ValidateService validateService = (ValidateService)facade.serviceProvider.GetService(typeof(ValidateService));

            try
            {
                validateService.Validate(vm);

                int result = await facade.Update(id, m, identityService.Username);

                return(NoContent());
            }
            catch (ServiceValidationExeption e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.BAD_REQUEST_STATUS_CODE, General.BAD_REQUEST_MESSAGE)
                    .Fail(e);
                return(BadRequest(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
Exemplo n.º 3
0
        public async Task Should_Error_Create_Data_date_more_than_expectedDeliveryDate()
        {
            PurchaseRequestViewModel viewModel = DataUtil.GetNewDataViewModel();

            viewModel.date = DateTimeOffset.MaxValue;
            var response = await this.Client.PostAsync(URI, new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Exemplo n.º 4
0
        public async Task Should_Success_Create_Data()
        {
            PurchaseRequestViewModel viewModel = DataUtil.GetNewDataViewModel();
            HttpContent httpContent            = new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType);

            httpContent.Headers.Add("x-timezone-offset", "0");
            var response = await this.Client.PostAsync(URI, httpContent);

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        }
Exemplo n.º 5
0
        public async Task Should_Error_Create_Invalid_Data_Item()
        {
            PurchaseRequestViewModel viewModel = DataUtil.GetNewDataViewModel();

            foreach (PurchaseRequestItemViewModel item in viewModel.items)
            {
                item.product  = null;
                item.quantity = 0;
            }
            var response = await this.Client.PostAsync(URI, new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Exemplo n.º 6
0
        public async Task Should_Error_Create_Invalid_Data()
        {
            PurchaseRequestViewModel viewModel = DataUtil.GetNewDataViewModel();

            viewModel.date     = DateTimeOffset.MinValue;
            viewModel.budget   = null;
            viewModel.unit     = null;
            viewModel.category = null;
            viewModel.items    = new List <PurchaseRequestItemViewModel> {
            };
            var response = await this.Client.PostAsync(URI, new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public async Task Should_Success_PRPost()
        {
            PurchaseRequest model = await DataUtil.GetTestData("dev2");

            PurchaseRequestViewModel viewModel = DataUtil.GetNewDataViewModel();

            viewModel._id = model.Id;
            List <PurchaseRequestViewModel> viewModelList = new List <PurchaseRequestViewModel> {
                viewModel
            };
            var response = await this.Client.PostAsync($"{URI}/post", new StringContent(JsonConvert.SerializeObject(viewModelList).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        }
        public IActionResult AddNewPRHeader(PurchaseRequestViewModel model)
        {
            var projectCode = model.PRHeaderDetail.ShortcutDimension2Code;

            if (projectCode == null)
            {
                projectCode = "";
            }
            //compare date
            DateTime now     = DateTime.Now;
            DateTime dummy   = new DateTime(1900, 1, 1);
            DateTime due     = Convert.ToDateTime(model.PRHeaderDetail.DueDate);
            TimeSpan compare = due - now;
            var      getDiff = compare.Days;

            if (getDiff < 14)
            {
                return(Json(new { status = false, message = "The minimum date of Receipt is 14 days from now" }));
            }
            else
            {
                var PRNO = newPRNO();

                //Insert Data
                var insert = new PurchaseRequisitionHeader
                {
                    RequisitionNo          = PRNO,
                    DueDate                = model.PRHeaderDetail.DueDate,
                    RequesterId            = model.PRHeaderDetail.RequesterId,
                    ShortcutDimension1Code = model.PRHeaderDetail.ShortcutDimension1Code,
                    ShortcutDimension2Code = projectCode,
                    ExpirationDate         = dummy,
                    OrderDate              = now,
                    Status       = 0,
                    Priority     = model.PRHeaderDetail.Priority,
                    RequestNotes = model.PRHeaderDetail.RequestNotes,
                    PurchaseNo   = "",
                    RowStatus    = 0,
                    CreatedBy    = model.PRHeaderDetail.RequesterId,
                    CreatedTime  = DateTime.Now,
                    LocationCode = model.PRHeaderDetail.LocationCode
                };
                _bmlContext.PurchaseRequisitionHeader.Add(insert);
                _bmlContext.SaveChanges();

                return(Json(new { status = true, message = "Data Saved succesfull" }));
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> GetAsync(int id)
        {
            try
            {
                var indexAcceptPdf = Request.Headers["Accept"].ToList().IndexOf("application/pdf");

                PurchaseRequest          model     = facade.ReadById(id);
                PurchaseRequestViewModel viewModel = mapper.Map <PurchaseRequestViewModel>(model);
                if (viewModel == null)
                {
                    throw new Exception("Invalid Id");
                }

                if (indexAcceptPdf < 0)
                {
                    return(Ok(new
                    {
                        apiVersion = ApiVersion,
                        statusCode = General.OK_STATUS_CODE,
                        message = General.OK_MESSAGE,
                        data = viewModel,
                    }));
                }
                else
                {
                    int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());

                    PurchaseRequestPDFTemplate PdfTemplate = new PurchaseRequestPDFTemplate();
                    MemoryStream stream = PdfTemplate.GeneratePdfTemplate(viewModel, clientTimeZoneOffset);

                    return(new FileStreamResult(stream, "application/pdf")
                    {
                        FileDownloadName = $"{viewModel.no}.pdf"
                    });
                }
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
        public IActionResult EditPRHeader(PurchaseRequestViewModel model)
        {
            var projectCode = model.PRHeaderDetail.ShortcutDimension2Code;

            if (projectCode == null)
            {
                projectCode = "";
            }

            //GET PR from DB
            var getPR = _bmlContext.PurchaseRequisitionHeader.SingleOrDefault(a => a.RequisitionNo == model.PRHeaderDetail.RequisitionNo);

            if (getPR == null)
            {
                return(Json(new { status = false, message = "Couldn't Find PR with PR Number : " + model.PRHeaderDetail.RequisitionNo }));
            }
            else
            {
                //compare Date Time
                DateTime orderdate = Convert.ToDateTime(getPR.OrderDate);
                DateTime dueDate   = Convert.ToDateTime(model.PRHeaderDetail.DueDate);
                TimeSpan compare   = dueDate - orderdate;
                var      getDiff   = compare.Days;
                if (getDiff < 14)
                {
                    return(Json(new { status = false, message = "The minimum Date of Receipt is 14 days, but this PR only " + getDiff + " days" }));
                }
                else
                {
                    //lakukan update
                    getPR.DueDate                = dueDate;
                    getPR.RequestNotes           = model.PRHeaderDetail.RequestNotes;
                    getPR.LocationCode           = model.PRHeaderDetail.LocationCode;
                    getPR.ShortcutDimension2Code = projectCode;
                    getPR.Priority               = model.PRHeaderDetail.Priority;
                    getPR.LastModifiedBy         = _userManager.GetUserName(User);
                    getPR.LastModifiedTime       = DateTime.Now;
                    _bmlContext.PurchaseRequisitionHeader.Update(getPR);
                    _bmlContext.SaveChanges();

                    return(Json(new { status = true, message = "Your File Saved Successfull" }));
                }
            }
        }
        public IActionResult Post([FromBody] PurchaseRequestViewModel vm)
        {
            PurchaseRequest m = _mapper.Map <PurchaseRequest>(vm);

            int Result = _facade.Create(m);

            /* TODO API Result */

            /* Dibawah ini hanya dummy */

            if (Result.Equals(0))
            {
                return(StatusCode(500));
            }
            else
            {
                return(Ok());
            }
        }
Exemplo n.º 12
0
        public async Task Should_Success_Update_Data()
        {
            PurchaseRequest model = await DataUtil.GetTestData("dev2");

            var responseGetById = await this.Client.GetAsync($"{URI}/{model.Id}");

            var json = await responseGetById.Content.ReadAsStringAsync();

            Dictionary <string, object> result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json.ToString());

            Assert.True(result.ContainsKey("apiVersion"));
            Assert.True(result.ContainsKey("message"));
            Assert.True(result.ContainsKey("data"));
            Assert.True(result["data"].GetType().Name.Equals("JObject"));

            PurchaseRequestViewModel viewModel = JsonConvert.DeserializeObject <PurchaseRequestViewModel>(result.GetValueOrDefault("data").ToString());

            var response = await this.Client.PutAsync($"{URI}/{model.Id}", new StringContent(JsonConvert.SerializeObject(viewModel).ToString(), Encoding.UTF8, MediaType));

            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        }
        public IActionResult AddPRNew()
        {
            var UserId   = _userManager.GetUserId(User);
            var userName = _userManager.GetUserName(User);

            ViewBag.userName = userName;
            var getUser = _mainSysContext.AspNetUsers.FirstOrDefault(a => a.Id == UserId);

            ViewBag.Department = getUser.Departement;

            //shortcut Dimension 2 code
            List <Models.BalimoonBML.DimensionValue> getShortcut2code = _bmlContext.DimensionValue.Where(a => a.DimensionCode == "PROJECT").ToList();

            ViewBag.ProjectCode = new SelectList(getShortcut2code, "DimensionValueCode", "DimensionValueName");

            //Location Code
            List <Models.BalimoonBML.Locations> getLocation = _bmlContext.Locations.ToList();

            ViewBag.LocationCode = new SelectList(getLocation, "LocationCode", "LocationName");

            //Priority
            List <Models.MainSystem.LookupField> Priority = _mainSysContext.LookupField.Where(a => a.LookupGroup == "Priority").ToList();

            ViewBag.Priority = new SelectList(Priority, "LookupCode", "LookupDescription");

            //Status
            List <Models.MainSystem.LookupField> Status = _mainSysContext.LookupField.Where(a => a.LookupGroup == "PurchaseStatus").ToList();

            ViewBag.Status = new SelectList(Status, "LookupCode", "LookupDescription");

            //Mendapat List Tabel
            var PRList = new PurchaseRequestViewModel();

            PRList.PRHeaderList = _bmlContext.PurchaseRequisitionHeader.Where(a => (a.CreatedBy == userName || a.RequesterId == userName || a.ShortcutDimension1Code == getUser.Departement) && a.Status == 0).ToList();

            return(View(PRList));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Post([FromBody] PurchaseRequestViewModel vm)
        {
            identityService.Token    = Request.Headers["Authorization"].First().Replace("Bearer ", "");
            identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;

            PurchaseRequest m = mapper.Map <PurchaseRequest>(vm);

            ValidateService validateService = (ValidateService)facade.serviceProvider.GetService(typeof(ValidateService));

            try
            {
                validateService.Validate(vm);

                int clientTimeZoneOffset = int.Parse(Request.Headers["x-timezone-offset"].First());
                int result = await facade.Create(m, identityService.Username, clientTimeZoneOffset);

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.CREATED_STATUS_CODE, General.OK_MESSAGE)
                    .Ok();
                return(Created(String.Concat(Request.Path, "/", 0), Result));
            }
            catch (ServiceValidationExeption e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.BAD_REQUEST_STATUS_CODE, General.BAD_REQUEST_MESSAGE)
                    .Fail(e);
                return(BadRequest(Result));
            }
            catch (Exception e)
            {
                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message)
                    .Fail();
                return(StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result));
            }
        }
        public MemoryStream GeneratePdfTemplate(PurchaseRequestViewModel viewModel, int clientTimeZoneOffset)
        {
            Font header_font  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11);
            Font normal_font  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            Font normal_font2 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font bold_font    = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);

            Document     document = new Document(PageSize.A5, 15, 15, 15, 15);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region Header

            string    companyNameString = "PT. MULTIYASA ABADI SENTOSA";
            Paragraph companyName       = new Paragraph(companyNameString, header_font)
            {
                Alignment = Element.ALIGN_CENTER
            };
            document.Add(companyName);

            string    companyAddressString = "BANARAN, GROGOL, SUKOHARJO";
            Paragraph companyAddress       = new Paragraph(companyAddressString, normal_font)
            {
                Alignment = Element.ALIGN_CENTER
            };
            companyAddress.SpacingAfter = 10f;
            document.Add(companyAddress);

            LineSeparator lineSeparator = new LineSeparator(1f, 100f, BaseColor.Black, Element.ALIGN_CENTER, 1);
            document.Add(lineSeparator);

            //string codeNoString = "FM-PB-00-06-006/R1";
            //Paragraph codeNo = new Paragraph(codeNoString, bold_font) { Alignment = Element.ALIGN_RIGHT };
            //codeNo.SpacingBefore = 5f;
            //document.Add(codeNo);

            string titleString = "ORDER PEMESANAN";
            bold_font.SetStyle(Font.UNDERLINE);
            Paragraph title = new Paragraph(titleString, bold_font)
            {
                Alignment = Element.ALIGN_CENTER
            };
            document.Add(title);
            bold_font.SetStyle(Font.NORMAL);

            #endregion

            #region Identity

            PdfPTable tableIdentity = new PdfPTable(3);
            tableIdentity.SetWidths(new float[] { 1f, 4.5f, 2.5f });
            PdfPCell cellIdentityContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellIdentityContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            cellIdentityContentLeft.Phrase = new Phrase("Bagian", normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.unit.name, normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("Sukoharjo, " + viewModel.date.GetValueOrDefault().ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font2);
            tableIdentity.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase("Budget", normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.budget.name, normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentity.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase("Nomor", normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.no, normal_font2);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentity.AddCell(cellIdentityContentRight);
            PdfPCell cellIdentity = new PdfPCell(tableIdentity); // dont remove
            tableIdentity.ExtendLastRow = false;
            document.Add(tableIdentity);

            #endregion

            string    firstParagraphString = "Mohon dibelikan/diusahakan barang tersebut dibawah ini :";
            Paragraph firstParagraph       = new Paragraph(firstParagraphString, normal_font2)
            {
                Alignment = Element.ALIGN_LEFT
            };
            firstParagraph.SpacingBefore = 10f;
            firstParagraph.SpacingAfter  = 10f;
            document.Add(firstParagraph);

            #region TableContent

            PdfPCell cellCenter = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellRight = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellLeft = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };

            PdfPTable tableContent = new PdfPTable(5);
            tableContent.SetWidths(new float[] { 1f, 4f, 7f, 3f, 4f });

            cellCenter.Phrase = new Phrase("NO", bold_font);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("KODE", bold_font);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("BARANG", bold_font);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("JUMLAH", bold_font);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("HARGA", bold_font);
            tableContent.AddCell(cellCenter);

            //for (int a = 0; a < 20; a++) // coba kalau banyak baris ^_^
            for (int indexItem = 0; indexItem < viewModel.items.Count; indexItem++)
            {
                PurchaseRequestItemViewModel item = viewModel.items[indexItem];

                cellCenter.Phrase = new Phrase((indexItem + 1).ToString(), normal_font2);
                tableContent.AddCell(cellCenter);

                cellLeft.Phrase = new Phrase(item.product.code, normal_font2);
                tableContent.AddCell(cellLeft);

                cellLeft.Phrase = new Phrase(item.product.name + Environment.NewLine + item.remark, normal_font2);
                tableContent.AddCell(cellLeft);

                cellCenter.Phrase = new Phrase(string.Format("{0:n2}", item.quantity) + $" {item.product.uom.unit}", normal_font2);
                tableContent.AddCell(cellCenter);

                cellCenter.Phrase = new Phrase(" ", normal_font2);
                tableContent.AddCell(cellCenter);
            }

            for (int i = 0; i < 5; i++)
            {
                tableContent.AddCell(cellCenter);
            }

            PdfPCell cellContent = new PdfPCell(tableContent); // dont remove
            tableContent.ExtendLastRow = false;
            tableContent.SpacingAfter  = 20f;
            document.Add(tableContent);

            #endregion

            #region Footer

            PdfPTable tableFooter = new PdfPTable(2);
            tableFooter.SetWidths(new float[] { 2f, 8f });
            PdfPCell cellFooterContent = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            cellFooterContent.Phrase = new Phrase("Kategori", normal_font2);
            tableFooter.AddCell(cellFooterContent);
            cellFooterContent.Phrase = new Phrase(": " + viewModel.category.name, normal_font2);
            tableFooter.AddCell(cellFooterContent);
            cellFooterContent.Phrase = new Phrase("Diminta Datang", normal_font2);
            tableFooter.AddCell(cellFooterContent);
            cellFooterContent.Phrase = new Phrase(": " + (viewModel.expectedDeliveryDate != null && viewModel.expectedDeliveryDate != DateTimeOffset.MinValue ? viewModel.expectedDeliveryDate.GetValueOrDefault().ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID")) : "-"), normal_font2);
            tableFooter.AddCell(cellFooterContent);
            cellFooterContent.Phrase = new Phrase("Keterangan", normal_font2);
            tableFooter.AddCell(cellFooterContent);
            cellFooterContent.Phrase = new Phrase(": " + viewModel.remark, normal_font2);
            tableFooter.AddCell(cellFooterContent);
            PdfPCell cellFooter = new PdfPCell(tableFooter); // dont remove
            tableFooter.ExtendLastRow = false;
            document.Add(tableFooter);

            #endregion

            #region TableSignature

            PdfPTable tableSignature = new PdfPTable(5);
            tableSignature.SetWidths(new float[] { 1f, 1f, 1f, 1f, 1f });

            cellCenter.Phrase = new Phrase("BAGIAN ANGGARAN", bold_font);
            tableSignature.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("ACC MENGETAHUI", bold_font);
            tableSignature.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("BAGIAN PEMBELIAN", bold_font);
            tableSignature.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("KEPALA BAGIAN", bold_font);
            tableSignature.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("YANG MEMERLUKAN", bold_font);
            tableSignature.AddCell(cellCenter);

            cellCenter.Phrase = new Phrase("\n\n\n\n");
            tableSignature.AddCell(cellCenter);
            tableSignature.AddCell(cellCenter);
            tableSignature.AddCell(cellCenter);
            tableSignature.AddCell(cellCenter);
            tableSignature.AddCell(cellCenter);

            PdfPCell cellSignature = new PdfPCell(tableSignature); // dont remove
            tableSignature.ExtendLastRow = false;
            tableSignature.SpacingBefore = 20f;
            tableSignature.SpacingAfter  = 20f;
            document.Add(tableSignature);

            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        //Untuk pindah ke form Edit Header, Add Line dan Edit Line
        public IActionResult AddPRNewDetailCSCSHTMLaqilhuiz(string ReQUest)
        {
            if (HttpContext.Session.GetString("email") == null)
            {
                var returnurl = "/PurchaseRequest/AddPRNewDetailCSCSHTMLaqilhuiz?ReQUest=" + ReQUest;
                return(RedirectToAction("Login", new RouteValueDictionary(
                                            new { Controller = "Account", Action = "Login", returnUrl = returnurl }
                                            )));
            }
            var UserId  = _userManager.GetUserId(User);
            var getUser = _mainSysContext.AspNetUsers.FirstOrDefault(a => a.Id == UserId);

            if (ReQUest == null)
            {
                return(View("_NotFound"));
            }
            else
            {
                ViewBag.PRNumber = ReQUest;
                PurchaseRequestViewModel model = new PurchaseRequestViewModel();
                model.PRHeaderDetail = _bmlContext.PurchaseRequisitionHeader.SingleOrDefault(a => a.RequisitionNo == ReQUest && a.Status == 0 && a.ShortcutDimension1Code == getUser.Departement);
                if (model.PRHeaderDetail == null)
                {
                    return(View("_NotFound"));
                }
                else
                {
                    //shortcut Dimension 2 code
                    List <Models.BalimoonBML.DimensionValue> getShortcut2code = _bmlContext.DimensionValue.Where(a => a.DimensionCode == "PROJECT").ToList();
                    ViewBag.ProjectCode = new SelectList(getShortcut2code, "DimensionValueCode", "DimensionValueName");

                    //Location Code
                    List <Models.BalimoonBML.Locations> getLocation = _bmlContext.Locations.ToList();
                    ViewBag.LocationCode = new SelectList(getLocation, "LocationCode", "LocationName");

                    //Priority
                    List <Models.MainSystem.LookupField> Priority = _mainSysContext.LookupField.Where(a => a.LookupGroup == "Priority").ToList();
                    ViewBag.Priority = new SelectList(Priority, "LookupCode", "LookupDescription");

                    //Status
                    List <Models.MainSystem.LookupField> Status = _mainSysContext.LookupField.Where(a => a.LookupGroup == "PurchaseStatus").ToList();
                    ViewBag.Status = new SelectList(Status, "LookupCode", "LookupDescription");

                    //Record Type
                    List <Models.MainSystem.LookupField> RecordType = _mainSysContext.LookupField.Where(a => a.LookupGroup == "RecordType").ToList();
                    ViewBag.RecordType = new SelectList(RecordType, "LookupCode", "LookupDescription");

                    var PRList = (from line in _bmlContext.PurchaseRequisitionLine
                                  join item in _bmlContext.Items on line.RecordNo equals item.ItemNo
                                  where line.DocumentNo == ReQUest
                                  select new ItemPRViewModel()
                    {
                        Item = item,
                        PRLine = line
                    }).ToList();
                    model.ItemsPRList = PRList;

                    //_bmlContext.PurchaseRequisitionLine.Where(a => a.DocumentNo == ReQUest).ToList();
                    return(View(model));
                }
            }
        }
        public async Task <IActionResult> AddLineItems(IFormFile gambarItem, PurchaseRequestViewModel model)
        {
            //make link to the PR images
            var    link1        = "wwwroot/dist/AppsImages/PR";
            var    link2        = "wwwroot\\dist\\AppsImages\\PR\\";
            string resultupload = "";
            //Upload The Images
            string upload = await _uploadImages.ImagesUpload(gambarItem, link1, link2);

            if (upload == "")
            {
                resultupload = "";
            }
            else if (upload != "File must be either .jpg, .jpeg, .png and Maximum Size is 4MB")
            {
                resultupload = upload;
            }
            else
            {
                resultupload = "";
            }
            //get not required input
            var vatProd      = model.PRLineDetail.VatprodPostingGroup;
            var Desc2        = model.PRLineDetail.Description2;
            var UoM          = model.PRLineDetail.UnitofMeasure;
            var VatBus       = model.PRLineDetail.VatbusPostingGroup;
            var InvenPost    = model.PRLineDetail.InventoryPostingGroup;
            var ItemCatCode  = model.PRLineDetail.ItemCategoryCode;
            var ProductGroup = model.PRLineDetail.ProductGroupCode;
            var GenProd      = model.PRLineDetail.GenProdPostingGroup;

            var a = gambarItem;

            //Change null to ""
            if (vatProd == null)
            {
                vatProd = "";
            }
            if (Desc2 == null)
            {
                Desc2 = "";
            }
            if (UoM == null)
            {
                UoM = "";
            }
            if (VatBus == null)
            {
                VatBus = "";
            }
            if (InvenPost == null)
            {
                InvenPost = "";
            }
            if (ItemCatCode == null)
            {
                ItemCatCode = "";
            }
            if (ProductGroup == null)
            {
                ProductGroup = "";
            }
            if (GenProd == null)
            {
                GenProd = "";
            }
            var SeqLineNumber = newSeqLineNoPR(model.PRLineDetail.DocumentNo);

            //Get Header PR
            var Header = _bmlContext.PurchaseRequisitionHeader.SingleOrDefault(a => a.RequisitionNo == model.PRLineDetail.DocumentNo);
            //Add PR Line to DB
            PurchaseRequisitionLine prLine = new PurchaseRequisitionLine()
            {
                RequisitionheaderId   = Header.RequisitionHeaderId,
                DocumentNo            = model.PRLineDetail.DocumentNo,
                SeqLineNo             = SeqLineNumber,
                RecordType            = model.PRLineDetail.RecordType,
                RecordNo              = model.PRLineDetail.RecordNo,
                Description           = model.PRLineDetail.Description,
                Description2          = Desc2,
                Quantity              = model.PRLineDetail.Quantity,
                UnitofMeasure         = UoM,
                VendorNo              = "",
                DirectUnitCost        = model.PRLineDetail.DirectUnitCost,
                VatbusPostingGroup    = VatBus,
                VatprodPostingGroup   = vatProd,
                InventoryPostingGroup = InvenPost,
                DueDate                = Header.DueDate,
                RequesterId            = _userManager.GetUserName(User),
                Confirmed              = 0,
                ShortcutDimension1Code = Header.ShortcutDimension1Code,
                ShortcutDimension2Code = Header.ShortcutDimension2Code,
                LocationCode           = Header.LocationCode,
                RecurringMethod        = 0,
                ExpirationDate         = Header.ExpirationDate,
                RecurringFrequency     = "",
                OrderDate              = Header.OrderDate,
                VendorItemNo           = "",
                SalesOrderNo           = "",
                SelltoCustomerNo       = "",
                ShiptoCode             = "",
                OrderAddressCode       = "",
                CurrencyCode           = "IDR",
                CurrencyFactor         = 1,
                ProdOrderNo            = "",
                VariantCode            = "",
                BinCode                = "",
                QtyperUnitofMeasure    = 1,
                UnitofMeasureCode      = UoM,
                QuantityBase           = model.PRLineDetail.Quantity,
                DemandType             = 0,
                DemandSubtype          = 0,
                DemandOrderNo          = "",
                DemandLineNo           = 0,
                DemandRefNo            = 0,
                Status                  = Header.Status,
                DemandDate              = Header.ExpirationDate,
                DemandQuantity          = 0,
                DemandQuantityBase      = 0,
                NeededQuantity          = 0,
                NeededQuantityBase      = 0,
                Reserve                 = 0,
                QtyperUomdemand         = 0,
                UnitOfMeasureCodeDemand = "",
                SupplyFrom              = "",
                OriginalItemNo          = "",
                OriginalVariantCode     = "",
                Level = 0,
                DemandQtyAvailable       = 0,
                UserId                   = "",
                ItemCategoryCode         = ItemCatCode,
                Nonstock                 = 0,
                PurchasingCode           = "",
                ProductGroupCode         = ProductGroup,
                TransferfromCode         = "",
                TransferShipmentDate     = Header.ExpirationDate,
                LineDiscountPercent      = 0,
                OrderPromisingSubLineNo  = 0,
                RoutingNo                = "",
                OperationNo              = "",
                WorkCenterNo             = "",
                ProdOrderLineNo          = 0,
                Mpsorder                 = 0,
                PlanningFlexibility      = 0,
                RoutingReferenceNo       = 0,
                GenProdPostingGroup      = GenProd,
                GenBusinessPostingGroup  = "",
                LowLevelCode             = 0,
                ProductionBomno          = "",
                RoutingVersionCode       = "",
                RoutingType              = 0,
                OriginalQuantity         = model.PRLineDetail.Quantity,
                FinishedQuantity         = 0,
                RemainingQuantity        = model.PRLineDetail.Quantity,
                OriginalDueDate          = Header.ExpirationDate,
                ScrapPercent             = 0,
                StartingDate             = Header.ExpirationDate,
                StartingTime             = Header.ExpirationDate,
                EndingDate               = Header.ExpirationDate,
                EndingTime               = Header.ExpirationDate,
                ProductionBomversionCode = "",
                IndirectCostPercent      = 0,
                OverheadRate             = 0,
                UnitCost                 = model.PRLineDetail.DirectUnitCost,
                CostAmount               = (model.PRLineDetail.Quantity * model.PRLineDetail.DirectUnitCost),
                ReplenishmentSystem      = 0,
                RefOrderNo               = "",
                RefOrderType             = 0,
                RefOrderStatus           = 0,
                RefLineNo                = 0,
                NoSeries                 = "",
                FinishedQtyBase          = 0,
                QuantityPo               = 0,
                RemainingQtyBase         = model.PRLineDetail.Quantity,
                RelatedtoPlanningLine    = 0,
                PlanningLevel            = 0,
                PlanningLineOrigin       = 0,
                ActionMessage            = 0,
                AcceptActionMessage      = 0,
                NetQuantityBase          = 0,
                StartingDateTime         = Header.ExpirationDate,
                EndingDateTime           = Header.ExpirationDate,
                OrderPromisingId         = "",
                OrderPromisingLineNo     = 0,
                OrderPromisingLineId     = 0,
                Priority                 = Header.Priority,
                RequestNotes             = Header.RequestNotes,
                RowStatus                = 0,
                CreatedBy                = _userManager.GetUserName(User),
                CreatedTime              = DateTime.Now,
                Picture                  = resultupload
            };

            _bmlContext.PurchaseRequisitionLine.Add(prLine);
            _bmlContext.SaveChanges();

            return(Json(new { status = true, message = "Your File Saved Successfull" }));
        }