Exemplo n.º 1
0
        public InsuranceDto GetInsurance(int modelId)
        {
            var dbinsurance = Get <ProductType>(p => p.Alias == ProductTypeEnum.Insurance.ToString());

            if (dbinsurance == null)
            {
                throw new Exception("insurance type not found");
            }
            var sin = GetSINByModelId(modelId, s => s.Passport);

            if (sin == null)
            {
                throw new Exception("sin not found");
            }
            var insurance = new InsuranceDto
            {
                BuyTime    = DateTime.MinValue,
                SkuName    = "Страховка отсутствует",
                LifeStyle  = "Страховка отсутствует",
                ShopName   = "Страховка отсутствует",
                PersonName = $"{sin.Passport?.PersonName}"
            };
            var lastIns = GetInsurance(modelId, r => r.Sku.Nomenklatura, r => r.Shop);

            if (lastIns != null)
            {
                insurance.SkuId     = lastIns.SkuId;
                insurance.BuyTime   = lastIns.DateCreated;
                insurance.SkuName   = lastIns.Sku.Name;
                insurance.LifeStyle = BillingHelper.GetLifestyle(lastIns.Sku.Nomenklatura.Lifestyle).ToString();
                insurance.ShopName  = lastIns.Shop.Name;
            }
            return(insurance);
        }
Exemplo n.º 2
0
        protected string GetWalletName(Wallet wallet, bool anon, List <SIN> sinCache, List <ShopWallet> shopCache, string owner = "")
        {
            if (wallet == null)
            {
                return(ErrorWalletName($"Передан пустой кошелек"));
            }
            switch (wallet.WalletType)
            {
            case (int)WalletTypes.Character:
                var sin = sinCache.FirstOrDefault(s => s.WalletId == wallet.Id);
                if (sin == null)
                {
                    return(owner);
                }
                return(BillingHelper.GetPassportName(sin.Passport, anon));

            case (int)WalletTypes.Corporation:
                return(ErrorWalletName($"Переводы корпорациям не реализованы wallet: {wallet.Id}"));

            case (int)WalletTypes.Shop:
                var shop = shopCache.FirstOrDefault(s => s.WalletId == wallet.Id);
                if (shop == null)
                {
                    return(ErrorWalletName($"Не найден shop для wallet {wallet.Id}"));
                }
                return($"{shop.Id} {shop.Name}");

            case (int)WalletTypes.MIR:
                return("MIR");

            default:
                return(string.Empty);
            }
        }
Exemplo n.º 3
0
        public ShopDto CreateOrUpdateShopWallet(int shopId = 0, decimal balance = 0, string name = "default shop", int lifestyle = 1, int ownerId = 0, List <int> specialisations = null, string comment = "", string location = "")
        {
            ShopWallet shop = null;

            if (shopId == 0)
            {
                var newWallet = CreateOrUpdateWallet(WalletTypes.Shop);
                shop = new ShopWallet
                {
                    Wallet  = newWallet,
                    OwnerId = ownerId
                };
                AddAndSave(shop);
                shopId = shop.Id;
            }
            else
            {
                shop = Get <ShopWallet>(w => w.Id == shopId, s => s.Wallet, s => s.Specialisations);
            }
            if (shop == null)
            {
                throw new BillingException("shop not found");
            }
            shop.Name           = name;
            shop.OwnerId        = ownerId;
            shop.Wallet.Balance = balance;
            shop.Comment        = comment;
            shop.Location       = location;
            var ls = BillingHelper.GetLifestyle(lifestyle);

            shop.LifeStyle = (int)ls;
            SaveContext();
            var dbSpecialisations = GetList <ShopSpecialisation>(s => s.ShopId == shop.Id);

            foreach (var shopspecialisation in dbSpecialisations)
            {
                Remove(shopspecialisation);
            }
            SaveContext();
            if (specialisations != null)
            {
                foreach (var specialisationId in specialisations)
                {
                    var specialisation = Get <Specialisation>(s => s.Id == specialisationId);
                    if (specialisation == null)
                    {
                        throw new Exception($"некорректные входные данные specialisation: {specialisation?.Id} ");
                    }
                    Add(new ShopSpecialisation {
                        ShopId = shopId, SpecialisationId = specialisationId
                    });
                }
                SaveContext();
            }
            shop = GetAsNoTracking <ShopWallet>(w => w.Id == shopId, s => s.Owner, s => s.Wallet, s => s.Specialisations);
            var dto = new ShopDto(ownerId, shop);

            return(dto);
        }
Exemplo n.º 4
0
 public ShopDetailedDto GetHackerDetailedShop(int shopId)
 {
     if (BillingHelper.IsShopAdmin(shopId))
     {
         throw new BillingException("доступ запрещен");
     }
     return(GetDetailedShop(shopId));
 }
Exemplo n.º 5
0
 public void StealShopMoney(int shopId, int modelTo, decimal amount, string comment)
 {
     if (BillingHelper.IsShopAdmin(shopId))
     {
         throw new BillingException("доступ запрещен");
     }
     MakeTransferLegSIN(shopId, modelTo, amount, comment);
 }
Exemplo n.º 6
0
 private BeatCharacterLocalDto AddLifeStyle(Wallet wallet, BeatCharacterLocalDto dto)
 {
     if (wallet.IsIrridium)
     {
         dto.IsIrridium = true;
         return(dto);
     }
     dto.Balance  = wallet.Balance;
     dto.Forecast = BillingHelper.GetForecast(wallet);
     return(dto);
 }
Exemplo n.º 7
0
        public void StealMoney(int modelFrom, int modelTo, decimal amount, string comment)
        {
            var from = GetSINByModelId(modelFrom, s => s.Character, s => s.Wallet);
            var to   = GetSINByModelId(modelTo, s => s.Character, s => s.Wallet);

            if (BillingHelper.IsAdmin(modelFrom))
            {
                throw new BillingException("У него нельзя воровать. Ваше местоположение зафиксировано, информация в нужные службы поступила");
            }
            MakeTransferSINSIN(from, to, amount, comment, false);
        }
Exemplo n.º 8
0
 public void HackShop(int shopId, int[] models)
 {
     if (BillingHelper.IsShopAdmin(shopId))
     {
         throw new BillingException("доступ запрещен");
     }
     if (models == null)
     {
         models = new int[0] {
         };
     }
     UpdateShopTrustedUsers(shopId, models.ToList());
 }
Exemplo n.º 9
0
        public NomenklaturaDto CreateOrUpdateNomenklatura(int id, string name, string code, int specialisationId, int lifestyle, decimal baseprice, int basecount, string description, string pictureurl, int externalId = 0)
        {
            Nomenklatura nomenklatura = null;

            if (id > 0)
            {
                nomenklatura = Get <Nomenklatura>(n => n.Id == id);
            }
            if (nomenklatura == null)
            {
                nomenklatura            = new Nomenklatura();
                nomenklatura.PictureUrl = UrlNotFound;
                nomenklatura.Code       = string.Empty;
                Add(nomenklatura);
            }
            nomenklatura.Name        = name;
            nomenklatura.Code        = code;
            nomenklatura.BasePrice   = baseprice;
            nomenklatura.Description = description;
            nomenklatura.PictureUrl  = pictureurl;
            if (externalId != 0)
            {
                nomenklatura.ExternalId = externalId;
            }
            nomenklatura.BaseCount = basecount;
            Specialisation specialisation = null;

            if (specialisationId > 0)
            {
                specialisation = Get <Specialisation>(p => p.Id == specialisationId);
            }
            else
            {
                specialisation = Get <Specialisation>(p => p.Id == nomenklatura.SpecialisationId);
            }
            if (specialisation == null)
            {
                throw new BillingException("specialisation not found");
            }
            nomenklatura.SpecialisationId = specialisation.Id;
            nomenklatura.Lifestyle        = lifestyle;
            nomenklatura.Lifestyle        = (int)BillingHelper.GetLifestyle(nomenklatura.Lifestyle);
            SaveContext();
            nomenklatura = GetAsNoTracking <Nomenklatura>(n => n.Id == nomenklatura.Id, n => n.Specialisation.ProductType);
            if (nomenklatura == null)
            {
                throw new Exception("Создать nomenklatura не получилось");
            }
            return(new NomenklaturaDto(nomenklatura, true));
        }
Exemplo n.º 10
0
        protected void RecalculateRenta(Renta renta, string qrDecoded, SIN newsin)
        {
            renta.SinId = newsin.Id;
            var anon = GetAnon(newsin.Character.Model);

            renta.CurrentScoring = newsin.Scoring.CurerentRelative + newsin.Scoring.CurrentFix;
            var gmdescript = BillingHelper.GetGmDescription(newsin.Passport, renta.Sku, anon);

            _ereminService.UpdateQR(qrDecoded, renta.BasePrice,
                                    BillingHelper.GetFinalPrice(renta),
                                    gmdescript,
                                    renta.Id,
                                    BillingHelper.GetLifestyle(renta.LifeStyle)).GetAwaiter().GetResult();
            SaveContext();
        }
Exemplo n.º 11
0
        protected Price CreateNewPrice(Sku sku, ShopWallet shop, SIN sin)
        {
            decimal modeldiscount;

            try
            {
                var eService = new EreminService();
                modeldiscount = eService.GetDiscount(sin.Character.Model, BillingHelper.GetDiscountType(sku.Nomenklatura.Specialisation.ProductType.DiscountType));
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
                modeldiscount = 1;
            }
            decimal discount = 1;

            if (sin.Passport.Mortgagee == sku.Corporation.Alias)
            {
                discount *= 0.9m;
            }
            discount *= modeldiscount;
            var currentScoring = sin.Scoring.CurrentFix + sin.Scoring.CurerentRelative;

            if (currentScoring == 0)
            {
                currentScoring = 1;
            }
            var price = new Price
            {
                Sku            = sku,
                Shop           = shop,
                BasePrice      = sku.Nomenklatura.BasePrice,
                CurrentScoring = currentScoring,
                DateCreated    = DateTime.Now.ToUniversalTime(),
                Discount       = discount,
                Sin            = sin,
                ShopComission  = BillingHelper.GetShopComission(shop.LifeStyle),
                ShopPrice      = BillingHelper.GetShopPrice(sku)
            };

            price.FinalPrice = BillingHelper.GetFinalPrice(price);
            Add(price);
            SaveContext();
            return(price);
        }
Exemplo n.º 12
0
        public MemoryStream LoadMainExcel()
        {
            var billing       = IocContainer.Get <IBillingManager>();
            var settings      = IocContainer.Get <ISettingsManager>();
            var sins          = billing.GetSinsInGame();
            var result        = new List <MainExcelDto>();
            var ikarkoef      = settings.GetDecimalValue(SystemSettingsEnum.ikar_k);
            var karmakoef     = settings.GetDecimalValue(SystemSettingsEnum.karma_k);
            var inflationkoef = settings.GetDecimalValue(SystemSettingsEnum.pre_inflation);
            var lifestyle     = BillingHelper.GetLifeStyleDto();

            foreach (var sin in sins)
            {
                var     allRents = billing.GetRentas(sin.Character.Model);
                decimal karma    = 0;
                try
                {
                    var eService = new EreminService();
                    karma = eService.GetCharacter(sin.Character.Model)?.workModel?.karma?.spent ?? 0;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

                var excelCharacter = new MainExcelDto
                {
                    Balance         = sin.Wallet.Balance,
                    PersonName      = sin.Passport?.PersonName,
                    KarmaKoef       = karmakoef,
                    InflationKoef   = inflationkoef,
                    ScoringFix      = sin.Scoring.CurrentFix,
                    ScoringRelative = sin.Scoring.CurerentRelative,
                    ModelId         = sin.Character.Model.ToString(),
                    LifeStyle       = lifestyle.GetLifeStyle(sin.Wallet).ToString(),
                    SumRents        = allRents.Sum,
                    Karma           = karma
                };
                result.Add(excelCharacter);
            }

            return(ExcelWriter.CreateExcelAsStream(result));
        }
Exemplo n.º 13
0
        public TransferSum GetTransfers(int modelId)
        {
            var result = new TransferSum();
            var sin    = GetSINByModelId(modelId, s => s.Wallet, s => s.Passport);

            if (sin == null)
            {
                throw new BillingException("sin not found");
            }
            var listFrom          = GetListAsNoTracking <Transfer>(t => t.WalletFromId == sin.WalletId, t => t.WalletFrom, t => t.WalletTo);
            var listFromTruncated = listFrom.Where(t => t.RentaId == null).ToList();
            var listTo            = GetListAsNoTracking <Transfer>(t => t.WalletToId == sin.WalletId, t => t.WalletFrom, t => t.WalletTo);
            var owner             = BillingHelper.GetPassportName(sin.Passport);

            result.Transfers = CreateTransfersDto(listFromTruncated, listTo, owner);
            result.Transfers.Insert(0, CreateFakeTransferDto(-1, listFrom.Where(r => r.RentaId != null && !r.Overdraft).Sum(t => t.Amount), false, "Выплаченная сумма по рентам", owner, false));
            result.Transfers.Insert(0, CreateFakeTransferDto(-2, listFrom.Where(r => r.RentaId != null && r.Overdraft).Sum(t => t.Amount), false, "Задолженность по рентам", owner, false));
            return(result);
        }
Exemplo n.º 14
0
        /// <summary>
        /// TODO need caching
        /// </summary>
        protected TransferDto CreateTransferDto(Transfer transfer, TransferType type, List <SIN> sinCache, List <ShopWallet> shopCache, string owner = "владелец кошелька", bool overdraft = false)
        {
            bool anon = transfer.Anonymous;

            return(new TransferDto
            {
                ModelId = "закрыто",
                Comment = transfer.Comment,
                TransferType = type.ToString(),
                Amount = BillingHelper.Round(transfer.Amount),
                NewBalance = overdraft ? 0 : type == TransferType.Incoming ? transfer.NewBalanceTo : transfer.NewBalanceFrom,
                OperationTime = transfer.OperationTime,
                From = GetWalletName(transfer.WalletFrom, anon, sinCache, shopCache, owner),
                To = GetWalletName(transfer.WalletTo, anon, sinCache, shopCache, owner),
                Anonimous = transfer.Anonymous,
                Id = transfer.Id,
                Overdraft = transfer.Overdraft,
                RentaId = transfer.RentaId
            });
        }
Exemplo n.º 15
0
        protected void CloseOverdraft(Renta renta, Wallet mir, SIN sin, bool first = false)
        {
            decimal comission;

            if (renta.FullPrice)
            {
                comission = BillingHelper.GetFinalPrice(renta);
            }
            else
            {
                comission = BillingHelper.CalculateComission(renta);
            }
            //create KPI here
            renta.Sku.Corporation.CurrentKPI += renta.ShopPrice;
            if (first)
            {
                renta.Sku.Corporation.SkuSold += renta.ShopPrice;
            }
            //comission
            AddNewTransfer(mir, renta.Shop.Wallet, comission, $"Рентное начисление: {renta.Sku.Name} в {renta.Shop.Name} от {sin.Passport.PersonName}", false, renta.Id, false);
        }
Exemplo n.º 16
0
        public void FillSku(int corporationId)
        {
            var corporation = Get <CorporationWallet>(c => c.Id == corporationId);

            if (corporation == null)
            {
                throw new BillingNotFoundException("Corporation not found");
            }
            var specialissations = GetList <CorporationSpecialisation>(c => c.CorporationId == corporationId);

            foreach (var specialisation in specialissations)
            {
                var nomenklaturas = GetList <Nomenklatura>(n => n.SpecialisationId == specialisation.SpecialisationId, n => n.Specialisation);
                foreach (var nomenklatura in nomenklaturas)
                {
                    var sku = Get <Sku>(s => s.NomenklaturaId == nomenklatura.Id && s.CorporationId == corporationId);
                    if (sku != null)
                    {
                        continue;
                    }
                    var enabled = true;
                    if (nomenklatura.Specialisation.Name.Contains("анлок"))
                    {
                        enabled = false;
                    }
                    var price = BillingHelper.GetSpecialisationPrice(specialisation, nomenklatura);
                    sku = new Sku
                    {
                        CorporationId  = corporationId,
                        Count          = nomenklatura.BaseCount,
                        Enabled        = enabled,
                        Name           = $"{nomenklatura.Name} ({corporation.Name})",
                        Nomenklatura   = nomenklatura,
                        NomenklaturaId = nomenklatura.Id,
                        Price          = price
                    };
                    AddAndSave(sku);
                }
            }
        }
Exemplo n.º 17
0
        public BalanceDto GetBalance(int modelId)
        {
            var sin      = GetSINByModelId(modelId, s => s.Wallet, s => s.Scoring, s => s.Passport.Metatype);
            var insur    = GetInsurance(modelId, r => r.Sku);
            var lics     = ProductTypeEnum.Licences.ToString();
            var licences = GetList <Renta>(r => r.Sku.Nomenklatura.Specialisation.ProductType.Alias == lics && r.SinId == sin.Id, r => r.Sku.Nomenklatura)
                           .OrderByDescending(r => r.DateCreated)
                           .GroupBy(l => l.Sku.NomenklaturaId)
                           .Select(g => g.FirstOrDefault()?.Sku?.Name)
                           .ToList();
            var lifestyle = BillingHelper.GetLifeStyleDto();
            var balance   = new BalanceDto(sin)
            {
                ModelId           = modelId,
                LifeStyle         = lifestyle.GetLifeStyle(sin.Wallet).ToString(),
                ForecastLifeStyle = lifestyle.GetForecastLifeStyle(sin.Wallet).ToString(),
                Insurance         = insur?.Sku?.Name ?? "нет страховки",
                Licenses          = licences
            };

            return(balance);
        }
Exemplo n.º 18
0
        public OrganisationViewModel GetAvailableOrganisations(int modelId)
        {
            var isAdmin = BillingHelper.IsAdmin(modelId);
            var model   = new OrganisationViewModel
            {
                CurrentModelId       = modelId,
                CurrentCharacterName = GetCharacterName(modelId)
            };
            var sin = GetSINByModelId(modelId);

            if (sin == null)
            {
                throw new BillingNotFoundException($"sin not found {modelId}");
            }
            model.Shops = GetShops(modelId, s => (isAdmin || s.OwnerId == modelId || s.TrustedUsers.Any(t => t.Model == modelId)));
            if (isAdmin)
            {
                model.Shops.ForEach(s => s.IsOwner = true);
            }
            model.Corporations = GetCorporationDtos(s => s.OwnerId == modelId || isAdmin);
            return(model);
        }
Exemplo n.º 19
0
        public async Task <TransferSum> GetTransfersAsync(int modelId)
        {
            var result = new TransferSum();
            var sin    = GetSINByModelId(modelId, s => s.Wallet, s => s.Passport);

            if (sin == null)
            {
                throw new BillingException("sin not found");
            }
            var owner    = BillingHelper.GetPassportName(sin.Passport);
            var listFrom = await GetListAsNoTrackingAsync <Transfer>(t => t.WalletFromId == sin.WalletId, t => t.WalletFrom, t => t.WalletTo);

            var listFromTruncated = listFrom.Where(t => t.RentaId == null).ToList();
            var listTo            = await GetListAsNoTrackingAsync <Transfer>(t => t.WalletToId == sin.WalletId, t => t.WalletFrom, t => t.WalletTo);

            var allTransfers = await CreateTransfersDtoAsync(listFromTruncated, owner, TransferType.Incoming);

            allTransfers.AddRange(await CreateTransfersDtoAsync(listTo, owner, TransferType.Outcoming));
            result.Transfers = allTransfers.OrderByDescending(t => t.OperationTime).ToList();
            result.Transfers.Insert(0, CreateFakeTransferDto(-1, listFrom.Where(r => r.RentaId != null && !r.Overdraft).Sum(t => t.Amount), false, "Выплаченная сумма по рентам", owner, false));
            result.Transfers.Insert(0, CreateFakeTransferDto(-2, listFrom.Where(r => r.RentaId != null && r.Overdraft).Sum(t => t.Amount), false, "Задолженность по рентам", owner, false));
            return(result);
        }
Exemplo n.º 20
0
        /// <summary>
        /// НЕ ВЫПОЛНЯЕТСЯ SAVECONTEXT
        /// </summary>
        protected void ProcessRenta(Renta renta, Wallet mir, SIN sin, bool first = false)
        {
            if (renta?.Shop?.Wallet == null ||
                renta?.Sku?.Corporation?.Wallet == null ||
                sin?.Character == null ||
                sin?.Wallet == null ||
                renta?.Sku?.Nomenklatura == null)
            {
                throw new Exception("Ошибка загрузки моделей по ренте");
            }
            var finalPrice = BillingHelper.GetFinalPrice(renta);

            //если баланс положительный
            if (sin.Wallet.Balance > 0)
            {
                AddNewTransfer(sin.Wallet, mir, finalPrice, $"Рентный платеж: { renta.Sku.Name} в {renta.Shop.Name}", false, renta.Id, false);
                CloseOverdraft(renta, mir, sin, first);
            }
            else
            {
                AddNewTransfer(sin.Wallet, mir, finalPrice, $"Рентный платеж: {renta.Sku.Name} в {renta.Shop.Name}", false, renta.Id, true);
            }
        }
Exemplo n.º 21
0
        public BeatCharacterLocalDto ProcessCharacterBeat(int sinId, WorkModelDto workDto, decimal K, JobLifeStyleDto lastdto)
        {
            var sw = new Stopwatch();

            sw.Start();
            var localDto = new BeatCharacterLocalDto();
            var sin      = BlockCharacter(sinId, s => s.Wallet, s => s.Character, s => s.Passport, s => s.Scoring);

            SaveContext();
            var     mir      = GetMIR();
            decimal income   = 0;
            decimal outcome  = 0;
            var     mortagee = GetMortagee(sin.Passport);

            //ability
            if (workDto.Dividends1)
            {
                var def1 = _settings.GetDecimalValue(SystemSettingsEnum.dividents1_k);
                var sum  = GetDividends(mortagee, 0.01m, def1);
                AddNewTransfer(mir, sin.Wallet, sum, "Дивиденды *");
                income += sum;
                localDto.SumDividends += sum;
            }
            if (workDto.Dividends2)
            {
                var def2 = _settings.GetDecimalValue(SystemSettingsEnum.dividents2_k);
                var sum  = GetDividends(mortagee, 0.03m, def2);
                AddNewTransfer(mir, sin.Wallet, sum, "Дивиденды **");
                income += sum;
                localDto.SumDividends += sum;
            }
            if (workDto.Dividends3)
            {
                var def3 = _settings.GetDecimalValue(SystemSettingsEnum.dividents3_k);
                var sum  = GetDividends(mortagee, 0.05m, def3);
                AddNewTransfer(mir, sin.Wallet, sum, "Дивиденды ***");
                income += sum;
                localDto.SumDividends += sum;
            }
            //karma
            if (workDto.KarmaCount > 0)
            {
                var     avg = lastdto.GetAvergeKarma();
                decimal x1  = 0;
                if (avg != 0)
                {
                    x1 = (lastdto.GetAvergeRents() * K) / lastdto.GetAvergeKarma();
                }
                else
                {
                    x1 = (lastdto.GetAvergeRents() * K) / 700;
                }
                if (x1 == 0)
                {
                    x1 = 0.3m;
                }
                var karmasum = x1 * workDto.KarmaCount;
                income            += karmasum;
                localDto.SumKarma += karmasum;
                AddNewTransfer(mir, sin.Wallet, karmasum, "Пассивный доход");
            }
            var swIncome = Cut(sw);
            //rentas
            var rentas = GetList <Renta>(r => r.SinId == sin.Id, r => r.Shop.Wallet, r => r.Sku.Corporation.Wallet, r => r.Sku.Nomenklatura);

            foreach (var renta in rentas)
            {
                ProcessRenta(renta, mir, sin);
            }
            var swRentas = Cut(sw);

            //overdrafts
            if (sin.Wallet.Balance > 0)
            {
                var allOverdrafts = GetList <Transfer>(t => t.Overdraft && t.WalletFromId == sin.Wallet.Id && t.RentaId > 0);
                foreach (var overdraft in allOverdrafts)
                {
                    overdraft.Overdraft = false;
                    var closingRenta = Get <Renta>(r => r.Id == overdraft.RentaId, r => r.Sku.Corporation, r => r.Shop.Wallet, r => r.Sku.Nomenklatura);
                    CloseOverdraft(closingRenta, mir, sin);
                }
            }
            var swoverdrafts = Cut(sw);

            //metatype
            if (sin.Passport.MetatypeId != sin.OldMetaTypeId)
            {
                var scoring = IoC.IocContainer.Get <IScoringManager>();
                scoring.OnMetatypeChanged(sin);
                sin.OldMetaTypeId = sin.Passport.MetatypeId;
            }
            //insurance
            var insurance = GetInsurance(sin.CharacterId);

            if (insurance?.LifeStyle != sin.OldInsurance)
            {
                if ((insurance?.LifeStyle ?? 0) > 0 != (sin.OldInsurance ?? 0) > 0)
                {
                    var scoring = IoC.IocContainer.Get <IScoringManager>();
                    scoring.OnInsuranceChanged(sin, (insurance?.LifeStyle ?? 0) > 0);
                }
                sin.OldInsurance = insurance?.LifeStyle;
            }
            //summary
            localDto.Scoringvalue = BillingHelper.GetFullScoring(sin.Scoring);
            //forecast
            outcome += rentas.Sum(r => BillingHelper.GetFinalPrice(r));
            if (workDto.StockGainPercentage > 0)
            {
                var stock = outcome * (workDto.StockGainPercentage / 100);
                income += stock;
                AddNewTransfer(mir, sin.Wallet, stock, "Игра на бирже");
            }
            localDto.SumRents       += outcome;
            sin.Wallet.IncomeOutcome = income - outcome;
            if (sin.Wallet.IsIrridium)
            {
                localDto.IsIrridium = true;
            }
            else
            {
                localDto.Balance  = sin.Wallet.Balance;
                localDto.Forecast = BillingHelper.GetForecast(sin.Wallet);
            }
            SaveContext();
            var swOther = Cut(sw);

            sw.Stop();
            sin.DebugTime = Serialization.Serializer.ToJSON(new { swIncome, swRentas, swoverdrafts, swOther });
            UnblockCharacter(sin);
            return(localDto);
        }
Exemplo n.º 22
0
        protected Renta CreateRenta(int modelId, int priceId, int beat, int count = 1)
        {
            var sin = BillingBlocked(modelId, s => s.Wallet, s => s.Character, s => s.Passport, s => s.Scoring);

            if (count == 0)
            {
                count = 1;
            }
            var price = Get <Price>(p => p.Id == priceId,
                                    p => p.Sku.Nomenklatura.Specialisation.ProductType,
                                    p => p.Sku.Corporation.Wallet,
                                    s => s.Shop.Wallet,
                                    s => s.Sin.Character);

            if (price == null)
            {
                throw new BillingException("Персональное предложение не найдено");
            }
            if (price.Confirmed)
            {
                throw new Exception("Персональным предложением уже воспользовались");
            }
            if (price.Sin.Character.Model != modelId)
            {
                throw new Exception("Персональное предложение заведено на другого персонажа");
            }
            var dateTill = price.DateCreated.AddMinutes(_settings.GetIntValue(SystemSettingsEnum.price_minutes));

            if (dateTill < DateTime.Now.ToUniversalTime())
            {
                throw new BillingException($"Персональное предложение больше не действительно, оно истекло {dateTill:HH:mm:ss}");
            }
            var allowed = SkuAllowed(price.ShopId, price.SkuId);

            if (allowed == null)
            {
                throw new BillingException("Sku недоступно для продажи в данный момент");
            }
            price.FinalPrice *= count;
            if (sin.Wallet.Balance - price.FinalPrice < 0)
            {
                throw new BillingException("Недостаточно средств");
            }

            price.Sku.Count -= count;
            var instantConsume = price.Sku.Nomenklatura.Specialisation.ProductType.InstantConsume;
            var anon           = GetAnon(sin.Character.Model);
            var gmdescript     = BillingHelper.GetGmDescription(sin.Passport, price.Sku, anon);
            var renta          = new Renta
            {
                BasePrice      = price.BasePrice,
                Sin            = sin,
                CurrentScoring = price.CurrentScoring,
                Sku            = price.Sku,
                DateCreated    = DateTime.Now.ToUniversalTime(),
                Discount       = price.Discount,
                ShopComission  = price.ShopComission,
                ShopPrice      = price.ShopPrice,
                ShopId         = price.ShopId,
                Shop           = price.Shop,
                HasQRWrite     = instantConsume ? false : BillingHelper.HasQrWrite(price.Sku.Nomenklatura.Code),
                PriceId        = priceId,
                Secret         = gmdescript,
                LifeStyle      = price.Sku.Nomenklatura.Lifestyle,
                Count          = count,
                FullPrice      = price.Sku.Nomenklatura.Specialisation.ProductType.Alias == ProductTypeEnum.Charity.ToString(),
                BeatId         = beat
            };

            Add(renta);
            price.Confirmed = true;
            SaveContext();
            ProcessBuyScoring(sin, price.Sku, price.Shop);
            var mir = GetMIR();

            ProcessRenta(renta, mir, sin, true);
            SaveContext();
            if (instantConsume)
            {
                var erService = new EreminService();
                erService.ConsumeFood(renta.Id, (Lifestyles)renta.LifeStyle, modelId).GetAwaiter().GetResult();
            }
            return(renta);
        }
Exemplo n.º 23
0
        private void InitEcoSecondStage(SIN sin)
        {
            if ((sin.Passport.MetatypeId ?? 0) > 5)
            {
                sin.EVersion = "4";
                SaveContext();
                return;
            }
            var joinchacter = Get <JoinCharacter>(jc => jc.CharacterId == sin.CharacterId);
            var fields      = GetList <JoinFieldValue>(jfv => jfv.JoinCharacterId == joinchacter.Id, jfv => jfv.JoinField);
            var insurance   = fields.FirstOrDefault(f => f.JoinField.Name == "Страховка");
            var lifestyle   = Lifestyles.Wood;


            CorporationWallet citizen;
            ShopWallet        shop;
            Sku sku;

            if (insurance != null)
            {
                lifestyle = BillingHelper.GetLifestyleFromJoin(insurance.Value);
            }
            sin.Wallet.Balance = GetStartBalance(lifestyle);
            var ls = (int)lifestyle;
            var pt = ProductTypeEnum.Insurance.ToString();

            if (lifestyle == Lifestyles.Wood)
            {
                citizen = Get <CorporationWallet>(c => c.Alias == "Omnistar");
                if (citizen == null)
                {
                    throw new BillingNotFoundException("Гражданство при инициализации не найдено");
                }
                shop = Get <ShopWallet>(s => s.Name == "МЧС");
            }
            else
            {
                if (lifestyle == Lifestyles.Iridium)
                {
                    sin.Wallet.IsIrridium = true;
                }
                else
                {
                    sin.Wallet.IsIrridium = false;
                }
                if (sin.Passport.Citizenship == "Россия")
                {
                    citizen = Get <CorporationWallet>(c => c.Alias == "Россия");
                    shop    = Get <ShopWallet>(s => s.Name == "МЧС");
                }
                else
                {
                    citizen = Get <CorporationWallet>(c => c.Alias == "Zurich-Orbital");
                    shop    = Get <ShopWallet>(s => s.Name == "CrashCart");
                }

                if (citizen == null)
                {
                    throw new BillingNotFoundException("Гражданство при инициализации не найдено");
                }
                if (shop == null)
                {
                    throw new BillingNotFoundException("Продавец страховки при инициализации не найден");
                }
            }
            sku = Get <Sku>(s => s.CorporationId == citizen.Id && s.Nomenklatura.Specialisation.ProductType.Alias == pt && s.Nomenklatura.Lifestyle == ls, s => s.Nomenklatura.Specialisation.ProductType, s => s.Corporation);
            if (sku == null)
            {
                throw new BillingNotFoundException("Страховка при инициализации не найдена");
            }
            if (shop == null)
            {
                throw new BillingNotFoundException("Магазин стартовой страховки не найден");
            }
            var price = CreateNewPrice(sku, shop, sin);
            var renta = CreateRenta(sin.Character.Model, price.Id, 0, 1);

            sin.EVersion = "4";
            SaveContext();
        }
Exemplo n.º 24
0
        private void WriteRenta(Renta renta, string qrDecoded)
        {
            var code = renta.Sku.Nomenklatura.Code;
            var pt   = ProductTypeEnum.Spirit.ToString();

            if (renta.Sku.Nomenklatura.Specialisation.ProductType.Alias == pt)
            {
                var magic = new MagicService();
                var intqr = int.Parse(qrDecoded);
                magic.PutSpiritInJar(intqr, code).GetAwaiter().GetResult();
                qrDecoded = $"spirit {qrDecoded}";
            }
            else
            {
                var name        = renta.Sku.Name;
                var description = renta.Sku.Nomenklatura.Description;
                _ereminService.WriteQR(qrDecoded, code, name, description, renta.Count, renta.BasePrice, BillingHelper.GetFinalPrice(renta), renta.Secret, renta.Id, (Lifestyles)renta.LifeStyle).GetAwaiter().GetResult();
                var oldQR = Get <Renta>(r => r.QRRecorded == qrDecoded);
                if (oldQR != null)
                {
                    oldQR.QRRecorded = $"{qrDecoded} deleted";
                }
            }
            renta.QRRecorded = qrDecoded;
        }
Exemplo n.º 25
0
        public List <InsolventDto> GetInsolvents()
        {
            var overdrafts = GetList <Transfer>(t => t.Overdraft == true);
            var listIds    = overdrafts.Select(s => s.WalletFromId).Distinct().ToList();
            var sins       = GetList <SIN>(s => listIds.Contains(s.WalletId ?? 0), s => s.Wallet, s => s.Passport, s => s.Character);
            var sinIds     = sins.Select(s => s.Id).ToList();
            var rents      = GetList <Renta>(r => sinIds.Contains(r.SinId ?? 0), r => r.Sku);
            var insolvents = new List <InsolventDto>();

            foreach (var sin in sins)
            {
                var personOverdrafts = overdrafts.Where(o => o.WalletFromId == sin.WalletId);
                var insolvent        = new InsolventDto
                {
                    Balance     = sin.Wallet.Balance,
                    Citizenship = sin.Passport.Citizenship,
                    ModelId     = sin.Character.Model,
                    SinText     = sin.Passport.Sin,
                    PersonName  = sin.Passport.PersonName,
                    IsIrridium  = sin.Wallet.IsIrridium
                };
                insolvent.SumOverdraft = personOverdrafts.Where(t => t.WalletFromId == sin.WalletId).Sum(s => s.Amount);
                insolvent.SumRents     = rents.Where(r => r.SinId == sin.Id).Sum(r => BillingHelper.GetFinalPrice(r));
                insolvent.Debts        = new List <Debt>();
                foreach (var personaloverdraft in personOverdrafts)
                {
                    var renta   = rents.FirstOrDefault(r => r.Id == personaloverdraft.RentaId);
                    var skuName = "взломано";
                    if (renta != null)
                    {
                        skuName = renta.Sku.Name;
                    }
                    var debt = new Debt
                    {
                        FinalPrice = personaloverdraft.Amount,
                        RentId     = personaloverdraft.RentaId ?? 0,
                        SkuName    = skuName
                    };
                    insolvent.Debts.Add(debt);
                }
                insolvents.Add(insolvent);
            }
            return(insolvents);
        }