public async Task <IActionResult> Post([FromBody] SPKDocsFromFinihsingOutsViewModel ViewModel)
        {
            try
            {
                identityService.Username = User.Claims.Single(p => p.Type.Equals("username")).Value;
                identityService.Token    = Request.Headers["Authorization"].FirstOrDefault().Replace("Bearer ", "");

                await iSPKDocs.Create(ViewModel, identityService.Username, identityService.Token);

                Dictionary <string, object> Result =
                    new ResultFormatter(ApiVersion, General.CREATED_STATUS_CODE, General.OK_MESSAGE)
                    .Ok();
                return(Created(String.Concat(Request.Path, "/", 0), 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 async Task <int> Create(SPKDocsFromFinihsingOutsViewModel viewModel, string username, string token)
        {
            int Created = 0;

            using (var transaction = this.dbContext.Database.BeginTransaction())
            {
                try
                {
                    List <SPKDocsItem> sPKDocsItems = new List <SPKDocsItem>();

                    foreach (var item in viewModel.Items)
                    {
                        var isDifferentSize = item.IsDifferentSize;
                        if (isDifferentSize == true)
                        {
                            foreach (var detail in item.Details)
                            {
                                var sizeId       = detail.Size.Id.ToString("00");
                                var counterId    = viewModel.counters._id.ToString("00");
                                var subCounterId = viewModel.subCounters._id.ToString("00");
                                var asal         = viewModel.SourceId.ToString("0");
                                var roCreatedUtc = viewModel.RoCreatedUtc;
                                var materialId   = viewModel.materials._id.ToString("00");

                                var barcode = asal + counterId + subCounterId + materialId + sizeId + roCreatedUtc;
                                Console.WriteLine("barcodefad " + barcode);
                                var itemx = GetItem(barcode);

                                if (itemx == null || itemx.Count() == 0) //barcode belum terdaftar, insert ke tabel items (BMS) terlebih dahulu
                                {
                                    ItemCoreViewModelUsername itemCore = new ItemCoreViewModelUsername
                                    {
                                        dataDestination = new List <ItemViewModelRead>
                                        {
                                            new ItemViewModelRead
                                            {
                                                ArticleRealizationOrder = viewModel.RONo,
                                                code        = barcode,
                                                name        = viewModel.Comodity.name,
                                                Size        = item.Size.Size,
                                                Uom         = item.Uom.Unit,
                                                ImagePath   = viewModel.ImagePath,
                                                ImgFile     = "",
                                                Tags        = "",
                                                Remark      = "",
                                                Description = "",
                                                _id         = 0
                                            }
                                        },
                                        color                  = viewModel.color,
                                        process                = viewModel.process,
                                        materials              = viewModel.materials,
                                        materialCompositions   = viewModel.materialCompositions,
                                        collections            = viewModel.collections,
                                        seasons                = viewModel.seasons,
                                        counters               = viewModel.counters,
                                        subCounters            = viewModel.subCounters,
                                        categories             = viewModel.categories,
                                        DomesticCOGS           = item.BasicPrice,
                                        DomesticRetail         = 0,
                                        DomesticSale           = item.BasicPrice + item.ComodityPrice,
                                        DomesticWholesale      = 0,
                                        InternationalCOGS      = 0,
                                        InternationalWholesale = 0,
                                        InternationalRetail    = 0,
                                        InternationalSale      = 0,
                                        ImageFile              = "",
                                        _id      = 0,
                                        Username = username,
                                        Token    = token,
                                        TotalQty = detail.Quantity
                                    };

                                    string itemsUri   = "items/finished-goods/item";
                                    var    httpClient = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                                    var    response   = await httpClient.PostAsync($"{APIEndpoint.Core}{itemsUri}", new StringContent(JsonConvert.SerializeObject(itemCore).ToString(), Encoding.UTF8, General.JsonMediaType));

                                    response.EnsureSuccessStatusCode();

                                    var item2 = GetItem2(barcode);

                                    sPKDocsItems.Add(new SPKDocsItem
                                    {
                                        ItemArticleRealizationOrder = viewModel.RONo,
                                        ItemCode         = barcode,
                                        ItemDomesticCOGS = item.BasicPrice,
                                        ItemDomesticSale = item.BasicPrice + item.ComodityPrice,
                                        ItemId           = item2.FirstOrDefault()._id,
                                        ItemName         = viewModel.Comodity.name,
                                        ItemSize         = detail.Size.Size,
                                        ItemUom          = item.Uom.Unit,
                                        Quantity         = detail.Quantity,
                                        Remark           = "",
                                        SendQuantity     = detail.Quantity,
                                    });
                                }
                                else // barcode sudah terdaftar
                                {
                                    var existItemId = itemx.FirstOrDefault()._id;
                                    ItemCoreViewModelUsername itemCore = new ItemCoreViewModelUsername
                                    {
                                        _id      = existItemId,
                                        Username = username,
                                        Token    = token,
                                        TotalQty = detail.Quantity
                                    };

                                    sPKDocsItems.Add(new SPKDocsItem
                                    {
                                        ItemArticleRealizationOrder = viewModel.RONo,
                                        ItemCode         = barcode,
                                        ItemDomesticCOGS = item.BasicPrice,
                                        ItemDomesticSale = item.BasicPrice + item.ComodityPrice,
                                        ItemId           = existItemId,
                                        ItemName         = viewModel.Comodity.name,
                                        ItemSize         = detail.Size.Size,
                                        ItemUom          = item.Uom.Unit,
                                        Quantity         = detail.Quantity,
                                        Remark           = "",
                                        SendQuantity     = detail.Quantity,
                                    });

                                    //update TotalQty di tabel Items
                                    string             itemPutUri = $"items/finished-goods/update-qty-by-id/{existItemId}";
                                    IHttpClientService httpClient = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                                    var response = await httpClient.PutAsync($"{APIEndpoint.Core}{itemPutUri}", new StringContent(JsonConvert.SerializeObject(itemCore).ToString(), Encoding.UTF8, General.JsonMediaType));

                                    if (response != null)
                                    {
                                        response.EnsureSuccessStatusCode();
                                    }
                                }
                            }
                        }
                        else
                        {
                            var sizeId       = item.Size.Id.ToString("00");
                            var counterId    = viewModel.counters._id.ToString("00");
                            var subCounterId = viewModel.subCounters._id.ToString("00");
                            var asal         = viewModel.SourceId.ToString("0");
                            var roCreatedUtc = viewModel.RoCreatedUtc;
                            var materialId   = viewModel.materials._id.ToString("00");

                            var barcode = asal + counterId + subCounterId + materialId + sizeId + roCreatedUtc;
                            Console.WriteLine("barcodefad " + barcode);
                            var itemx = GetItem(barcode);

                            if (itemx == null || itemx.Count() == 0) //barcode belum terdaftar, insert ke tabel items (BMS) terlebih dahulu
                            {
                                ItemCoreViewModelUsername itemCore = new ItemCoreViewModelUsername
                                {
                                    dataDestination = new List <ItemViewModelRead>
                                    {
                                        new ItemViewModelRead
                                        {
                                            ArticleRealizationOrder = viewModel.RONo,
                                            code        = barcode,
                                            name        = viewModel.Comodity.name,
                                            Size        = item.Size.Size,
                                            Uom         = item.Uom.Unit,
                                            ImagePath   = viewModel.ImagePath,
                                            ImgFile     = "",
                                            Tags        = "",
                                            Remark      = "",
                                            Description = "",
                                            _id         = 0
                                        }
                                    },
                                    color                  = viewModel.color,
                                    process                = viewModel.process,
                                    materials              = viewModel.materials,
                                    materialCompositions   = viewModel.materialCompositions,
                                    collections            = viewModel.collections,
                                    seasons                = viewModel.seasons,
                                    counters               = viewModel.counters,
                                    subCounters            = viewModel.subCounters,
                                    categories             = viewModel.categories,
                                    DomesticCOGS           = item.BasicPrice,
                                    DomesticRetail         = 0,
                                    DomesticSale           = item.BasicPrice + item.ComodityPrice,
                                    DomesticWholesale      = 0,
                                    InternationalCOGS      = 0,
                                    InternationalWholesale = 0,
                                    InternationalRetail    = 0,
                                    InternationalSale      = 0,
                                    ImageFile              = "",
                                    _id      = 0,
                                    Username = username,
                                    Token    = token,
                                    TotalQty = item.Quantity
                                };

                                string itemsUri   = "items/finished-goods/item";
                                var    httpClient = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                                var    response   = await httpClient.PostAsync($"{APIEndpoint.Core}{itemsUri}", new StringContent(JsonConvert.SerializeObject(itemCore).ToString(), Encoding.UTF8, General.JsonMediaType));

                                response.EnsureSuccessStatusCode();

                                var item2 = GetItem2(barcode);

                                sPKDocsItems.Add(new SPKDocsItem
                                {
                                    ItemArticleRealizationOrder = viewModel.RONo,
                                    ItemCode         = barcode,
                                    ItemDomesticCOGS = item.BasicPrice,
                                    ItemDomesticSale = item.BasicPrice + item.ComodityPrice,
                                    ItemId           = item2.FirstOrDefault()._id,
                                    ItemName         = viewModel.Comodity.name,
                                    ItemSize         = item.Size.Size,
                                    ItemUom          = item.Uom.Unit,
                                    Quantity         = item.Quantity,
                                    Remark           = "",
                                    SendQuantity     = item.Quantity,
                                });
                            }
                            else // barcode sudah terdaftar
                            {
                                var existItemId = itemx.FirstOrDefault()._id;
                                ItemCoreViewModelUsername itemCore = new ItemCoreViewModelUsername
                                {
                                    _id      = existItemId,
                                    Username = username,
                                    Token    = token,
                                    TotalQty = item.Quantity
                                };

                                sPKDocsItems.Add(new SPKDocsItem
                                {
                                    ItemArticleRealizationOrder = viewModel.RONo,
                                    ItemCode         = barcode,
                                    ItemDomesticCOGS = item.BasicPrice,
                                    ItemDomesticSale = item.BasicPrice + item.ComodityPrice,
                                    ItemId           = existItemId,
                                    ItemName         = viewModel.Comodity.name,
                                    ItemSize         = item.Size.Size,
                                    ItemUom          = item.Uom.Unit,
                                    Quantity         = item.Quantity,
                                    Remark           = "",
                                    SendQuantity     = item.Quantity,
                                });

                                //update TotalQty di tabel Items
                                string             itemPutUri = $"items/finished-goods/update-qty-by-id/{existItemId}";
                                IHttpClientService httpClient = (IHttpClientService)serviceProvider.GetService(typeof(IHttpClientService));
                                var response = await httpClient.PutAsync($"{APIEndpoint.Core}{itemPutUri}", new StringContent(JsonConvert.SerializeObject(itemCore).ToString(), Encoding.UTF8, General.JsonMediaType));

                                if (response != null)
                                {
                                    response.EnsureSuccessStatusCode();
                                }
                            }
                        }
                    }

                    var packingListCode = GeneratePackingList();

                    SPKDocs data = new SPKDocs()
                    {
                        Code                 = GenerateCode("EFR-PK/PBJ"),
                        Date                 = viewModel.FinishingOutDate,
                        DestinationId        = (long)viewModel.DestinationStorageId,
                        DestinationCode      = viewModel.DestinationStorageCode,
                        DestinationName      = viewModel.DestinationStorageName,
                        IsDistributed        = false,
                        IsReceived           = false,
                        PackingList          = packingListCode,
                        Password             = "******",
                        Reference            = packingListCode,
                        SourceId             = (long)viewModel.SourceStorageId,
                        SourceCode           = viewModel.SourceStorageCode,
                        SourceName           = viewModel.SourceStorageName,
                        Weight               = 0,
                        FinishingOutIdentity = viewModel.FinishingOutIdentity,
                        Items                = sPKDocsItems
                    };

                    foreach (var i in data.Items)
                    {
                        EntityExtension.FlagForCreate(i, username, USER_AGENT);
                    }
                    EntityExtension.FlagForCreate(data, username, USER_AGENT);
                    dbContext.Add(data);

                    Created = await dbContext.SaveChangesAsync();

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw new Exception(e.Message);
                }
            }

            return(Created);
        }
        public void should_Success_Instantiate()
        {
            var dateTimeOffset = DateTimeOffset.Now.Date;

            var listItem = new List <SPKDocItemsFromFinihsingOutsViewModel>()
            {
                new SPKDocItemsFromFinihsingOutsViewModel()
                {
                    Quantity = 20,
                    Size     = new SizeObj()
                    {
                        Id   = 12345,
                        Size = "S"
                    },
                    Uom = new Uom()
                    {
                        Id   = 1,
                        Unit = "PCS"
                    },
                    BasicPrice      = 1000,
                    ComodityPrice   = 10000,
                    IsDifferentSize = true,
                    Details         = new List <Details>()
                    {
                        new Details()
                        {
                            ParentProduct = new Product()
                            {
                                Id   = 1,
                                Name = "Baju",
                                Code = "1231"
                            },
                            Size = new SizeObj()
                            {
                                Id   = 1,
                                Size = "S"
                            },
                            Uom = new Uom()
                            {
                                Id   = 1,
                                Unit = "PCS"
                            },
                            Quantity = 10
                        },
                        new Details()
                        {
                            ParentProduct = new Product()
                            {
                                Id   = 1,
                                Name = "Baju",
                                Code = "1231"
                            },
                            Size = new SizeObj()
                            {
                                Id   = 2,
                                Size = "M"
                            },
                            Uom = new Uom()
                            {
                                Id   = 1,
                                Unit = "PCS"
                            },
                            Quantity = 10
                        }
                    }
                }
            };

            SPKDocsFromFinihsingOutsViewModel dto = new SPKDocsFromFinihsingOutsViewModel
            {
                FinishingOutDate = dateTimeOffset,
                UnitTo           = new UnitObj()
                {
                    Id   = 1,
                    code = "1",
                    name = "name"
                },
                Unit = new UnitObj()
                {
                    Id   = 1,
                    code = "1",
                    name = "name"
                },
                PackingList     = "123",
                Password        = "******",
                IsDifferentSize = true,
                Weight          = 0,
                Comodity        = new Comodity()
                {
                    code = "1",
                    id   = 1,
                    name = "name"
                },
                process = new ItemArticleProcesViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                materialCompositions = new ItemArticleMaterialCompositionViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                materials = new ItemArticleMaterialViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                collections = new ItemArticleCollectionViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                seasons = new ItemArticleSeasonViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                counters = new ItemArticleCounterViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                subCounters = new ItemArticleSubCounterViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                categories = new ItemArticleCategoryViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                color = new ItemArticleColorViewModel()
                {
                    _id  = 1,
                    code = "1",
                    name = "name"
                },
                RONo                   = "123",
                ImagePath              = "/sales/",
                ImgFile                = "imgFile",
                Items                  = listItem,
                SourceStorageId        = 1,
                SourceStorageName      = "storage",
                SourceStorageCode      = "code",
                RoCreatedUtc           = "2110",
                SourceId               = 1,
                DestinationStorageName = "destination",
                DestinationStorageCode = "code",
                DestinationStorageId   = 1
            };

            Assert.Equal(dto.FinishingOutDate, dateTimeOffset);
            Assert.NotNull(dto.UnitTo);
            Assert.NotNull(dto.Unit);
            Assert.Equal(dto.PackingList, "123");
            Assert.Equal(dto.Password, "1");
            Assert.Equal(dto.IsDifferentSize, true);
            Assert.Equal(dto.Weight, 0);
            Assert.NotNull(dto.Comodity);
            Assert.NotNull(dto.process);
            Assert.NotNull(dto.materialCompositions);
            Assert.NotNull(dto.materials);
            Assert.NotNull(dto.collections);
            Assert.NotNull(dto.seasons);
            Assert.NotNull(dto.counters);
            Assert.NotNull(dto.subCounters);
            Assert.NotNull(dto.categories);
            Assert.NotNull(dto.color);
            Assert.Equal(dto.RONo, "123");
            Assert.Equal(dto.ImagePath, "/sales/");
            Assert.Equal(dto.ImgFile, "imgFile");
            Assert.NotEmpty(dto.Items);
            Assert.Equal(dto.SourceStorageId, 1);
            Assert.Equal(dto.SourceStorageName, "storage");
            Assert.Equal(dto.SourceStorageCode, "code");
            Assert.Equal(dto.RoCreatedUtc, "2110");
            Assert.Equal(dto.SourceId, 1);
            Assert.Equal(dto.DestinationStorageId, 1);
            Assert.Equal(dto.DestinationStorageName, "destination");
            Assert.Equal(dto.DestinationStorageCode, "code");
        }