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 async Task <int> CreateForPOS(TransferOutDoc model2, string username, int clientTimeZoneOffset = 7)
        {
            int Created = 0;

            using (var transaction = this.dbContext.Database.BeginTransaction())
            {
                try
                {
                    EntityExtension.FlagForCreate(model2, username, USER_AGENT);
                    foreach (var i in model2.Items)
                    {
                        var inventorymovement = new InventoryMovement();
                        var inven             = dbContext.Inventories.Where(x => x.ItemCode == i.ItemCode && x.StorageId == model2.SourceId).FirstOrDefault();
                        if (inven != null)
                        {
                            inventorymovement.Before = inven.Quantity;
                            inven.Quantity           = inven.Quantity - i.Quantity;
                        }
                        inventorymovement.After                      = inventorymovement.Before - i.Quantity;
                        inventorymovement.Date                       = DateTimeOffset.UtcNow;
                        inventorymovement.ItemCode                   = i.ItemCode;
                        inventorymovement.ItemDomesticCOGS           = i.DomesticCOGS;
                        inventorymovement.ItemDomesticRetail         = i.DomesticRetail;
                        inventorymovement.ItemDomesticWholeSale      = i.DomesticWholeSale;
                        inventorymovement.ItemDomesticSale           = i.DomesticSale;
                        inventorymovement.ItemId                     = i.ItemId;
                        inventorymovement.ItemInternationalCOGS      = 0;
                        inventorymovement.ItemInternationalRetail    = 0;
                        inventorymovement.ItemInternationalSale      = 0;
                        inventorymovement.ItemInternationalWholeSale = 0;
                        inventorymovement.ItemName                   = i.ItemName;
                        inventorymovement.ItemSize                   = i.Size;
                        inventorymovement.ItemUom                    = i.Uom;
                        inventorymovement.Quantity                   = i.Quantity;
                        inventorymovement.StorageCode                = model2.SourceCode;
                        inventorymovement.StorageId                  = model2.SourceId;
                        inventorymovement.StorageName                = model2.SourceName;
                        inventorymovement.Type                       = "OUT";
                        inventorymovement.Reference                  = model2.Code;
                        inventorymovement.Remark                     = model2.Remark;
                        inventorymovement.StorageIsCentral           = model2.SourceName.Contains("GUDANG") ? true : false;
                        EntityExtension.FlagForCreate(inventorymovement, username, USER_AGENT);
                        dbSetInventoryMovement.Add(inventorymovement);

                        EntityExtension.FlagForCreate(i, username, USER_AGENT);

                        //update TotalQty di tabel Items
                        var existItemId = (int)i.ItemId;
                        ItemCoreViewModelUsername itemCore = new ItemCoreViewModelUsername
                        {
                            _id      = existItemId,
                            Username = username,
                            Token    = "Bearer ",
                            TotalQty = i.Quantity
                        };

                        string             itemPutUri = $"items/finished-goods/reduce-qty-by-id/{i.ItemId}";
                        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));

                        response.EnsureSuccessStatusCode();
                    }

                    dbSet.Add(model2);
                    Created = await dbContext.SaveChangesAsync();

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