public void Search_suppliers() { session.Save(DataMother.CreateSupplier()); Flush(); Maintainer.MaintainIntersection(session, client, client.Orgs().First()); var suppliers = controller.SearchSuppliers(client.Id, "тест"); Assert.That(suppliers.Length, Is.GreaterThan(0)); }
public void Disabled_suppliers() { var supplier = DataMother.CreateSupplier(x => x.Name = Guid.NewGuid().ToString()); session.Save(supplier); Maintainer.MaintainIntersection(supplier, session); user.DisablePrice(session, supplier.Prices[0].Id); var result = filter.Find(true); Assert.That(result.Count, Is.GreaterThan(0)); result.Each(x => x.ForExport = true); var item = result.FirstOrDefault(x => x.UserId == user.Id.ToString()); Assert.IsNotNull(item, $"не найдена запись для пользователя {user.Id}"); Assert.AreEqual(item.DisabledSupName, supplier.Name); }
public void Set_costs_noising_except_one_supplier() { var supplier = DataMother.CreateSupplier(); MakeNameUniq(supplier); Maintainer.MaintainIntersection(supplier, session); Refresh(); Css("#drugstore_NoiseCosts").Click(); var select = new SelectElement((RemoteWebElement)SearchV2("#drugstore_NoiseCostExceptSupplier_Id", supplier.Name)); Assert.That(select.SelectedOption.Text, Is.StringEnding(supplier.Name)); ClickButton("Сохранить"); AssertText("Сохранено"); session.Refresh(settings); Assert.That(settings.FirmCodeOnly, Is.EqualTo(supplier.Id)); }
public void AddRegion(uint id) { var supplier = DbSession.Load <Supplier>(id); var edit = new RegionEdit(DbSession, supplier, Admin); PropertyBag["supplier"] = supplier; PropertyBag["edit"] = edit; PropertyBag["EmailContactType"] = ContactType.Email; PropertyBag["PhoneContactType"] = ContactType.Phone; if (IsPost) { SetSmartBinder(AutoLoadBehavior.NullIfInvalidKey); Bind(edit, "edit"); SetBinder(new DataBinder()); var contacts = BindObject <Contact[]>("contacts"); if (IsValid(edit)) { supplier.MergePerson(ContactGroupType.General, new Person(edit.RequestedBy, contacts)); supplier.AddRegion(edit.Region, DbSession); if (edit.ShouldNotify()) { Mail().RegionAdded(edit); RedminePostIssue(new { subject = edit.Subject(), description = edit.Body(), assigned_to_id = Config.RedmineAssignedTo }); } DbSession.Save(edit.GetAuditRecord()); DbSession.Save(supplier); Maintainer.MaintainIntersection(supplier, DbSession); Notify("Регион добавлен"); RedirectToAction("Show", new { id = supplier.Id }); } } }
public void Add_offer_matrix_exclude() { var supplier = DataMother.CreateMatrix(); Maintainer.MaintainIntersection(session, client, client.Orgs().First()); FlushAndCommit(); Css("#drugstore_EnableOfferMatrix").Click(); var select = Search("Фармаимпекс", "Ассортиментный прайс для матрицы закупок"); Assert.That(select.SelectedItem, Is.EqualTo("Фармаимпекс - Матрица")); var excludes = ((Table)Css("#excludes")); excludes.Css("input[value='Добавить']").Click(); excludes.Css(".term").TypeText("Фармаимпекс"); excludes.Css(".search[type=button]").Click(); Thread.Sleep(1000); Assert.That(excludes.Css("div.search select").SelectedItem, Is.StringEnding("Фармаимпекс")); Click("Сохранить"); AssertText("Сохранено"); Click("Настройка"); AssertText("Фармаимпекс - Матрица"); Assert.That(browser.SelectList(Find.ByName("drugstore.OfferMatrixType")).SelectedItem, Is.EqualTo("Белый список")); excludes = ((Table)Css("#excludes")); Assert.That(excludes.Text, Is.StringContaining("Фармаимпекс")); session.Refresh(client); Assert.That(client.Settings.OfferMatrixPrice.Name, Is.EqualTo("Матрица")); Assert.That(client.Settings.OfferMatrix, Is.Not.Null); Assert.That(client.Settings.OfferMatrixType, Is.EqualTo(MatrixType.WhiteList)); Assert.That(client.Settings.OfferMatrixExcludes.Count, Is.EqualTo(1)); Assert.That(client.Settings.OfferMatrixExcludes[0].Name, Is.EqualTo(supplier.Name)); }
protected override void Process() { Maintainer.MaintainIntersection(Session, "", _ => {}); }
public void RegisterSupplier( [DataBind("supplierContacts")] Contact[] supplierContacts, ulong homeRegion, [DataBind("regionSettings")] RegionSettings[] regionSettings, [DataBind("options")] AdditionalSettings options, [DataBind("payer")] Payer payer, uint?existingPayerId, [DataBind("userContacts")] Contact[] userContacts, [DataBind("userPersons")] Person[] userPersons, string additionalEmailsForSendingCard, string comment) { var supplier = new Supplier(); supplier.RegionMask = regionSettings.GetBrowseMask(); SetARDataBinder(AutoLoadBehavior.NewRootInstanceIfInvalidKey); BindObjectInstance(supplier, "supplier"); SetBinder(new DataBinder()); var currentPayer = RegisterPayer(options, payer, existingPayerId, supplier.Name, supplier.FullName); supplier.HomeRegion = DbSession.Load <Region>(homeRegion); supplier.Payer = currentPayer; supplier.Account = new SupplierAccount(supplier); supplier.ContactGroupOwner = new ContactGroupOwner(supplier.GetAditionalContactGroups()); supplier.Registration = new RegistrationInfo(Admin); var user = new User(supplier.Payer, supplier); BindObjectInstance(user, "user"); if (!IsValid(supplier, user, options)) { RegisterSupplier(); PropertyBag["options"] = options; PropertyBag["supplier"] = supplier; PropertyBag["user"] = user; PropertyBag["options"] = options; return; } var tokens = DbSession.Query <FederalSupplierToken>().ToList(); supplier.IsFederal = tokens.Select(x => x.Name) .Any(x => supplier.Name.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0 || supplier.FullName.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0); supplier.ContactGroupOwner.AddContactGroup(new ContactGroup(ContactGroupType.MiniMails)); currentPayer.Suppliers.Add(supplier); currentPayer.UpdatePaymentSum(); AddContacts(supplier.ContactGroupOwner, supplierContacts); supplier.OrderRules.Add(new OrderSendRules(Defaults, supplier)); DbSession.Save(supplier); foreach (var group in supplier.ContactGroupOwner.ContactGroups) { var persons = BindObject <List <Person> >(group.Type + "Persons"); var contacts = BindObject <List <Contact> >(group.Type + "Contacts"); group.Persons = persons; group.Contacts = contacts; } var groups = BindObject <RegionalDeliveryGroup[]>("orderDeliveryGroup"); foreach (var group in groups) { group.Region = DbSession.Load <Region>(group.Region.Id); group.Name = "Доставка заказов " + group.Region.Name; group.ContactGroupOwner = supplier.ContactGroupOwner; supplier.ContactGroupOwner.ContactGroups.Add(group); //повторная валидация, тк когда производился binding валидация не прошла //тк не было заполнено поле Name Validator.IsValid(group); } foreach (var group in supplier.ContactGroupOwner.ContactGroups) { group.Adopt(); DbSession.Save(group); group.Persons.Each(p => DbSession.Save(p)); } DbSession.Flush(); DbSession.Query <Region>() .Where(r => (r.Id & supplier.RegionMask) > 0) .Each(r => supplier.AddRegion(r, DbSession)); CreateSupplier(supplier); Maintainer.MaintainIntersection(supplier, DbSession); user.UpdateContacts(userContacts); foreach (var person in userPersons) { user.AddContactPerson(person.Name); } user.AssignDefaultPermission(DbSession); user.Setup(DbSession); var password = user.CreateInAd(Session); supplier.AddBillingComment(comment); Mailer.SupplierRegistred(supplier, comment); //Создание директорий для поставщика на фтп supplier.CreateDirs(); var log = new PasswordChangeLogEntity(user.Login); if (options.SendRegistrationCard) { log = SendRegistrationCard(log, user, password.Password, additionalEmailsForSendingCard); } string smsLog = ""; if (options.SendSmsToUser) { var phonesForSendToUserArray = user.GetPhonesForSendingSms().Select(x => x.Number).ToArray(); smsLog = smsLog + " " + ReportHelper.SendSmsPasswordToUser(user, password.Password, phonesForSendToUserArray); } if (options.SendSmsToAdmin) { var phonesForSendToAdminArray = GetPhoneSupportByRegionForSms(user.RootService.HomeRegion.Id); smsLog = smsLog + " " + ReportHelper.SendSmsToRegionalAdmin(user, password.Password, phonesForSendToAdminArray); } log.SmsLog = smsLog; DbSession.Save(log); if (options.FillBillingInfo) { Redirect("Register", "RegisterPayer", new { id = supplier.Payer.Id, showRegistrationCard = options.ShowRegistrationCard, passwordId = password.PasswordId }); } else if (supplier.Users.Count > 0 && options.ShowRegistrationCard) { Redirect("main", "report", new { id = supplier.Users.First().Id, passwordId = password.PasswordId }); } else { Notify("Регистрация завершена успешно"); Redirect("Suppliers", "Show", new { id = supplier.Id }); } }
public void Save(Supplier supplier, DataSet data, string host, ref string message) { var pricesDataAdapter = new MySqlDataAdapter(); pricesDataAdapter.DeleteCommand = new MySqlCommand( @" Set @InHost = ?UserHost; Set @InUser = ?UserName; delete from usersettings.PriceItems where id in (select pc.priceItemId from usersettings.pricescosts pc where pc.PriceCode = ?PriceCode); set @maxReplacePrice = (SELECT max(pd.PriceCode) FROM usersettings.pricesdata p join usersettings.pricesdata pd on pd.FirmCode = p.Firmcode and pd.PriceCode <> ?PriceCode and pd.enabled and pd.agencyenabled where p.pricecode = ?PriceCode and exists( select pd1.pricecode from usersettings.pricesregionaldata pd1, usersettings.pricesregionaldata pd2 where pd1.PriceCode = p.PriceCode and pd2.RegionCode = pd1.RegionCode and pd2.PriceCode = pd.PriceCode )); update ordersold.ordershead o set priceCode = @maxReplacePrice where priceCode = ?PriceCode; DELETE FROM PricesData WHERE PriceCode = ?PriceCode; DELETE FROM Customers.Intersection WHERE PriceId = ?PriceCode; DELETE FROM PricesRegionalData WHERE PriceCode = ?PriceCode; "); pricesDataAdapter.DeleteCommand.Parameters.AddWithValue("?UserHost", host); pricesDataAdapter.DeleteCommand.Parameters.AddWithValue("?UserName", SecurityContext.Administrator.UserName); pricesDataAdapter.DeleteCommand.Parameters.Add("?PriceCode", MySqlDbType.Int32, 0, "PriceCode"); pricesDataAdapter.InsertCommand = new MySqlCommand( @" SET @InHost = ?UserHost; SET @InUser = ?UserName; INSERT INTO PricesData SET UpCost = ?UpCost, PriceType = ?PriceType, CostType = ?CostType, Enabled = ?Enabled, AgencyEnabled = ?AgencyEnabled, BuyingMatrix = ?BuyingMatrix, IsLocal = ?IsLocal, FirmCode = ?ClientCode; SET @InsertedPriceCode = Last_Insert_ID(); INSERT INTO farm.formrules() VALUES(); SET @NewFormRulesId = Last_Insert_ID(); INSERT INTO farm.sources(RequestInterval) VALUES(IF(?PriceType=1, 86400, NULL)); SET @NewSourceId = Last_Insert_ID(); INSERT INTO usersettings.PriceItems(FormRuleId, SourceId) VALUES(@NewFormRulesId, @NewSourceId); SET @NewPriceItemId = Last_Insert_ID(); INSERT INTO PricesCosts (PriceCode, PriceItemId) SELECT @InsertedPriceCode, @NewPriceItemId; SET @NewPriceCostId:=Last_Insert_ID(); INSERT INTO farm.costformrules (CostCode) SELECT @NewPriceCostId; call UpdateCostType(@InsertedPriceCode, ?CostType); INSERT INTO pricesregionaldata ( regioncode, pricecode, enabled, basecost ) SELECT r.RegionCode, p.PriceCode, if(p.pricetype<>1, 1, 0), @NewPriceCostId FROM pricesdata p, Customers.Suppliers s, farm.regions r WHERE p.PriceCode = @InsertedPriceCode AND p.FirmCode = s.Id AND (r.RegionCode & s.RegionMask > 0) AND not exists ( SELECT * FROM pricesregionaldata prd WHERE prd.PriceCode = p.PriceCode AND prd.RegionCode = r.RegionCode ); select @NewPriceCostId; "); pricesDataAdapter.InsertCommand.Parameters.AddWithValue("?UserHost", host); pricesDataAdapter.InsertCommand.Parameters.AddWithValue("?UserName", SecurityContext.Administrator.UserName); pricesDataAdapter.InsertCommand.Parameters.AddWithValue("?ClientCode", supplier.Id); pricesDataAdapter.InsertCommand.Parameters.Add("?UpCost", MySqlDbType.Decimal, 0, "UpCost"); pricesDataAdapter.InsertCommand.Parameters.Add("?PriceType", MySqlDbType.Int32, 0, "PriceType"); pricesDataAdapter.InsertCommand.Parameters.Add("?Enabled", MySqlDbType.Bit, 0, "Enabled"); pricesDataAdapter.InsertCommand.Parameters.Add("?AgencyEnabled", MySqlDbType.Bit, 0, "AgencyEnabled"); pricesDataAdapter.InsertCommand.Parameters.Add("?BuyingMatrix", MySqlDbType.Bit, 0, "BuyingMatrix"); pricesDataAdapter.InsertCommand.Parameters.Add("?PriceCode", MySqlDbType.Int32, 0, "PriceCode"); pricesDataAdapter.InsertCommand.Parameters.Add("?CostType", MySqlDbType.Int32, 0, "CostType"); pricesDataAdapter.InsertCommand.Parameters.Add("?IsLocal", MySqlDbType.Bit, 0, "IsLocal"); pricesDataAdapter.UpdateCommand = new MySqlCommand( @" SET @InHost = ?UserHost; SET @InUser = ?UserName; UPDATE pricesdata SET UpCost = ?UpCost, PriceType = ?PriceType, Enabled = ?Enabled, AgencyEnabled = ?AgencyEnabled, BuyingMatrix = ?BuyingMatrix, IsLocal = ?IsLocal WHERE PriceCode = ?PriceCode; UPDATE farm.sources fs JOIN Usersettings.PriceItems pi ON fs.Id = pi.SourceId JOIN Usersettings.PricesCosts pc ON pi.Id = pc.PriceItemId AND pc.PriceCode = ?PriceCode SET fs.RequestInterval = IF(?PriceType = 1, 86400, NULL); call UpdateCostType(?PriceCode, ?CostType); "); pricesDataAdapter.UpdateCommand.Parameters.AddWithValue("?UserHost", host); pricesDataAdapter.UpdateCommand.Parameters.AddWithValue("?UserName", SecurityContext.Administrator.UserName); pricesDataAdapter.UpdateCommand.Parameters.Add("?UpCost", MySqlDbType.Decimal, 0, "UpCost"); pricesDataAdapter.UpdateCommand.Parameters.Add("?PriceType", MySqlDbType.Int32, 0, "PriceType"); pricesDataAdapter.UpdateCommand.Parameters.Add("?Enabled", MySqlDbType.Bit, 0, "Enabled"); pricesDataAdapter.UpdateCommand.Parameters.Add("?AgencyEnabled", MySqlDbType.Bit, 0, "AgencyEnabled"); pricesDataAdapter.UpdateCommand.Parameters.Add("?BuyingMatrix", MySqlDbType.Bit, 0, "BuyingMatrix"); pricesDataAdapter.UpdateCommand.Parameters.Add("?PriceCode", MySqlDbType.Int32, 0, "PriceCode"); pricesDataAdapter.UpdateCommand.Parameters.Add("?CostType", MySqlDbType.Int32, 0, "CostType"); pricesDataAdapter.UpdateCommand.Parameters.Add("?IsLocal", MySqlDbType.Bit, 0, "IsLocal"); var regionalSettingsDataAdapter = new MySqlDataAdapter(); regionalSettingsDataAdapter.UpdateCommand = new MySqlCommand( @" SET @InHost = ?UserHost; SET @InUser = ?UserName; UPDATE usersettings.regionaldata SET AdminMail = ?AdminMail, TmpMail = ?TmpMail, SupportPhone = ?SupportPhone, Enabled = ?Enabled, `Storage` = ?Storage WHERE RowId = ?Id; "); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?AdminMail", MySqlDbType.VarString, 0, "AdminMail"); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?TmpMail", MySqlDbType.VarString, 0, "TmpMail"); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?SupportPhone", MySqlDbType.VarString, 0, "SupportPhone"); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?Enabled", MySqlDbType.Bit, 0, "Enabled"); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?Storage", MySqlDbType.Bit, 0, "Storage"); regionalSettingsDataAdapter.UpdateCommand.Parameters.Add("?Id", MySqlDbType.Int32, 0, "RowID"); regionalSettingsDataAdapter.UpdateCommand.Parameters.AddWithValue("?UserHost", host); regionalSettingsDataAdapter.UpdateCommand.Parameters.AddWithValue("?UserName", SecurityContext.Administrator.UserName); var updateIntersection = data.Tables["Prices"].Rows.Cast <DataRow>().Any(r => r.RowState == DataRowState.Added); var modifiedIntersection = data.Tables["Prices"].Rows.Cast <DataRow>().Where(r => r.RowState == DataRowState.Modified); var vipChangeFlag = false; var modifiedVipPriced = modifiedIntersection.Where(dataRow => Convert.ToInt32(dataRow["PriceType"]) == (int)PriceType.Vip); foreach (var dataRow in modifiedVipPriced) { //Тут нужна доп. проверка на VIP, так как то что VIP прайс был изменен еще не означает, что там было измененно именно поле Типа. //А сообщение надо выводить только в случае изменения типа прайса на VIP var list = DbSession.Query <Intersection>().Where(i => i.Price.Id == Convert.ToUInt32(dataRow["PriceCode"]) && i.Price.PriceType != PriceType.Vip).ToList(); foreach (var inter in list) { inter.AvailableForClient = false; DbSession.Save(inter); vipChangeFlag = true; } } if (vipChangeFlag) { message = "Все клиенты были отключены от VIP прайсов"; } var connection = (MySqlConnection)DbSession.Connection; pricesDataAdapter.InsertCommand.Connection = connection; pricesDataAdapter.UpdateCommand.Connection = connection; pricesDataAdapter.DeleteCommand.Connection = connection; regionalSettingsDataAdapter.UpdateCommand.Connection = connection; pricesDataAdapter.Update(data.Tables["Prices"]); regionalSettingsDataAdapter.Update(data.Tables["RegionSettings"]); var currentSupplier = DbSession.Get <Supplier>(supplier.Id); BindRule(currentSupplier, data); DbSession.Save(currentSupplier); if (updateIntersection) { var addedPriceId = currentSupplier.Prices.Max(p => p.Id); Maintainer.MaintainIntersection(supplier, DbSession); DbSession.CreateSQLQuery( @" DROP TEMPORARY TABLE IF EXISTS tmp; CREATE TEMPORARY TABLE tmp ENGINE MEMORY SELECT adr.Id, rootAdr.SupplierDeliveryId FROM Customers.AddressIntersection adr join Customers.Intersection ins on ins.Id = adr.IntersectionId join pricesdata as rootPrice on rootPrice.PriceCode = (select min(pricecode) from pricesdata as p where p.firmcode = :supplierId ) join Customers.Intersection rootIns on rootIns.PriceId = rootPrice.PriceCode and rootIns.ClientId = ins.ClientId and rootIns.RegionId = ins.RegionId join Customers.AddressIntersection rootAdr on rootadr.AddressId = adr.AddressId and rootAdr.IntersectionId = rootIns.Id WHERE ins.PriceId = :priceId ; UPDATE Customers.AddressIntersection adr SET SupplierDeliveryId = (select tmp.SupplierDeliveryId from tmp tmp where tmp.Id = adr.Id limit 1) WHERE Exists(select 1 from Customers.Intersection ins where ins.Id = adr.IntersectionId and ins.PriceId = :priceId );") .SetParameter("priceId", addedPriceId) .SetParameter("supplierId", supplier.Id) .ExecuteUpdate(); } }
public void SetRegionalCostToIntersectionTest() { // создаем нового поставщика var supplier = DataMother.CreateSupplier(); // назначаем регионы Белгород и Воронеж supplier.RegionMask = 1 | 2; supplier.Prices[0].Costs[0].Name = "Базовая"; Save(supplier); Flush(); // добавляем новую ценовую колонку к прайсу var price = supplier.Prices[0]; price.Costs.Add(new Cost { Price = price, PriceItem = price.Costs[0].PriceItem, Name = "Новая" }); price.Costs[1].CostFormRule = new CostFormRule { Cost = price.Costs[1], FieldName = "" }; // добавляем новые региональные настройки и выставляем там базовой ценой только что добавленную var regionalData = new PriceRegionalData { Enabled = true, Price = price, Region = session.Query <Region>().First(t => t.Id == 2), Cost = price.Costs[1] }; price.RegionalData.Add(regionalData); Save(price); Flush(); // вставка в intersection Maintainer.MaintainIntersection(supplier, session); // проверяем, что все вставилось с правильной базовой ценой var intersection = session.Query <Intersection>().Where(i => i.Price.Id == price.Id); foreach (var intersectionItem in intersection) { if (intersectionItem.Region == regionalData.Region) { Assert.That(intersectionItem.Cost == price.Costs[1]); } else { Assert.That(intersectionItem.Cost == price.Costs[0]); } } // создаем нового клиента в регионе Белгород var client = DataMother.TestClient((c) => { c.HomeRegion = regionalData.Region; c.MaskRegion = regionalData.Region.Id; c.Settings.WorkRegionMask = regionalData.Region.Id; c.Settings.OrderRegionMask = regionalData.Region.Id; }); Save(client); Flush(); // проверяем, что ему добавилась Белгородская базовая цена intersection = session.Query <Intersection>().Where(i => i.Price.Id == price.Id && i.Client == client); foreach (var intersectionItem in intersection) { Assert.That(intersectionItem.Cost == price.Costs[1]); } // создаем клиента в Воронеже client = DataMother.TestClient(); Save(client); Flush(); // проверяем, что у него установлена Воронежская базовая цена intersection = session.Query <Intersection>().Where(i => i.Price.Id == price.Id && i.Client == client); foreach (var intersectionItem in intersection) { Assert.That(intersectionItem.Cost == price.Costs[0]); } }