private Field Free(string DirEmployeeLogin, string DirEmployeePswd, bool bEncode) { Field field = new Field(); #region Проверяем if (String.IsNullOrEmpty(DirEmployeeLogin) && String.IsNullOrEmpty(DirEmployeePswd)) { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg4; return(field); } #endregion #region Декодируем if (bEncode) { Account.EncodeDecode encode = new Account.EncodeDecode(); DirEmployeeLogin = encode.UnionDecode(DirEmployeeLogin); field.LoginFull = DirEmployeeLogin; DirEmployeePswd = encode.UnionDecode(DirEmployeePswd); } #endregion #region Проверяем Логин и Пароль using (DbConnectionSklad db = new DbConnectionSklad("ConnStr")) { db.Database.Connection.Open(); var query = db.DirEmployees.Where(x => x.DirEmployeeLogin == DirEmployeeLogin && x.DirEmployeePswd == DirEmployeePswd && x.Del == false && x.DirEmployeeActive == true).ToList(); if (query.Count > 0) { Models.Sklad.Dir.DirEmployee dirEmployee = query[0]; field.Access = true; field.DirEmployeeID = Convert.ToInt32(dirEmployee.DirEmployeeID); //field.SysDirRightsID = dirEmployee.SysDirRightsID; } else { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg4; return(field); } } #endregion return(field); }
private bool FreeUpdate(string AdminsLogin, string AdminsPswd, bool bEncode) { #region Проверяем if (String.IsNullOrEmpty(AdminsLogin) && String.IsNullOrEmpty(AdminsPswd)) { return(false); } #endregion #region Декодируем if (bEncode) { Account.EncodeDecode encode = new Account.EncodeDecode(); AdminsLogin = encode.UnionDecode(AdminsLogin); AdminsPswd = encode.UnionDecode(AdminsPswd); } #endregion #region Проверяем Логин и Пароль using (DbConnectionSklad db = new DbConnectionSklad("ConnStr")) { db.Database.Connection.Open(); var query = db.DirEmployees.Where(x => x.DirEmployeeLogin == AdminsLogin && x.DirEmployeePswd == AdminsPswd && x.Del == false && x.DirEmployeeActive == true).ToList(); if (query.Count > 0) { Models.Sklad.Dir.DirEmployee dirEmployee = query[0]; //Только с правами Администратора можно обновлять! /*if (dirEmployee.SysDirRightsID == 1) return true; * else return false;*/ return(true); } else { return(false); } } #endregion }
public async Task<IHttpActionResult> PutDirWarehouse(HttpRequestMessage request) //HttpPostedFileBase upload { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)); //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) /* int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocAccounts")); if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); */ if(field.DirEmployeeID != 1) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); //Разные Функции function.NumberDecimalSeparator(); //Получам настройки sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); //Параметры sheetName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sheetName", true) == 0).Value; DirContractorIDOrg = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value); DirContractorID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorID", true) == 0).Value); DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value); #endregion #region Сохранение OleDbConnection OleDbConn = null; try { //Алгоритм: //0. Проверка //1. Генерируем ID-шник "SysGens" //2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID //3. Считываем Эксель файл // [Код товара], [Категория], [Товар] //Получаем категорию "APPLE/ iPhone 4S/ Распродажа/ Распродажа Swarovski /" //Разделитель "/" и убираем первый пробел //Проверяем каждую получиную категорию: есть ли связка (Sub, Name) //Если нет - вносим категорию, а потом товар: ([Код товара], [Товар]) //Если есть - вносим товар: ([Код товара], [Товар]) // *** Важно *** *** *** //1.Находим максимальный код группы //2.Создаём коды групп (Макс + 1) //3.Создаём коды товаров(из Эксель) #region 0. Проверка *** *** *** *** *** *** *** if (!Request.Content.IsMimeMultipartContent()) Ok(returnServer.Return(false, "{" + "'msgType':'1', 'msg':'" + Classes.Language.Sklad.Language.msg57(0) + "'}")); #endregion #region 1. Генерируем ID-шник "SysGens" *** *** *** *** *** *** *** Models.Sklad.Sys.SysGen sysGen = new Models.Sklad.Sys.SysGen(); sysGen.SysGenDisc = ""; sysGen.SysGenID = null; //if (!ModelState.IsValid) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)); //return BadRequest(ModelState); db.Entry(sysGen).State = EntityState.Added; await db.SaveChangesAsync(); #endregion #region 2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID *** *** *** *** *** *** *** string filePatch = ""; var provider = new MultipartMemoryStreamProvider(); string root = System.Web.HttpContext.Current.Server.MapPath("~/UsersTemp/FileStock/"); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { if (file.Headers.ContentDisposition.FileName != null) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var ext = Path.GetExtension(filename); filePatch = root + field.DirCustomersID + "_" + sysGen.SysGenID + ext; byte[] fileArray = await file.ReadAsByteArrayAsync(); using (System.IO.FileStream fs = new System.IO.FileStream(filePatch, System.IO.FileMode.Create)) //root + filename { await fs.WriteAsync(fileArray, 0, fileArray.Length); } } } #endregion #region 3. Получаем максимальный код группы var queryMaxGroupID = await Task.Run(() => ( from x in db.DirNomens where x.DirNomenCategoryID == null select x ).MaxAsync(x => x.DirNomenID)); iMaxGroupID = queryMaxGroupID + 1; if (iMaxGroupID == null || iMaxGroupID == 0) iMaxGroupID = 1; #endregion #region 4. Считываем Эксель файл if (filePatch.Length > 0) { //1. Получаем категорию "APPLE/ iPhone 4S/ Распродажа/ Распродажа Swarovski /" //2. Разделитель "/" и убираем первый пробел //3. Проверяем каждую получиную категорию: есть ли связка (Sub, Name) //4. Если нет - вносим категорию, а потом товар: ([Код товара], [Товар]) //5. Если есть - вносим товар: ([Код товара], [Товар]) string sExcelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePatch + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\""; //8.0 using (OleDbConn = new OleDbConnection(sExcelConnectionString)) { OleDbConn.Open(); using (OleDbCommand OleDbCmd = new OleDbCommand("", OleDbConn)) { #region 1. Таблица "Товар" OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$]"; OleDbCmd.Parameters.Clear(); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { while (dr.Read()) { if (dr["Код товара"].ToString().Length == 5) { //Read string DirNomenID = dr["Код товара"].ToString(); string GroupList = dr["Категория"].ToString(); string DirNomenName = dr["Товар"].ToString(); //Create Group in database await Task.Run(() => GroupCreate(Convert.ToInt32(DirNomenID), GroupList, DirNomenName)); } else { alCodeNot.Add(dr["Код товара"].ToString() + " - " + dr["Категория"].ToString() + " - " + dr["Товар"].ToString()); //... } } ts.Commit(); } } #endregion #region 2. Таблицы: Характеристики, Приходная накладная (Шапка + Спецификация), Остатки, Партии. (Новый алгоритм алгоритм: одна приходная накладная) //1. Надо получить все точки из Эксель (GROUP BY) //2. И делать SELECT по точкам, что бы сформировать приходные накладные по точкам OleDbCmd.CommandText = "SELECT [Точка] FROM [" + sheetName + "$] GROUP BY [Точка] ORDER BY [Точка]"; OleDbCmd.Parameters.Clear(); ArrayList alDirWarehouseID = new ArrayList(); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { while (dr.Read()) { alDirWarehouseID.Add(dr["Точка"].ToString()); } } //Формируем "Приходные накладные" using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { for (int i = 0; i < alDirWarehouseID.Count; i++) { Models.Sklad.Doc.DocPurch docPurch = new Models.Sklad.Doc.DocPurch(); ArrayList alWrite = new ArrayList(); //OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Дата=@pDate"; OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Точка=@Точка"; // ORDER BY [Код товара], [Дата] DESC OleDbCmd.Parameters.Clear(); OleDbCmd.Parameters.AddWithValue("@Точка", alDirWarehouseID[i].ToString()); using (OleDbDataReader dr = OleDbCmd.ExecuteReader()) { while (dr.Read()) { if (dr["Код товара"].ToString().Length == 5) { Field1 field1 = new Field1(); field1.DirNomenID = Convert.ToInt32(dr["Код товара"].ToString()); field1.DocDate = dr["Дата"].ToString(); //field1.DirWarehouseID = ReturnDirWarehouseID(dr["Точка"].ToString()); field1.DirWarehouseID = await Task.Run(() => ReturnDirWarehouseID(dr["Точка"].ToString())); field1.Quantity = Convert.ToInt32(dr["Остаток"].ToString()); field1.PriceVAT = Convert.ToDouble(dr["Закуп цена за ед"].ToString()); field1.PriceCurrency = Convert.ToDouble(dr["Закуп цена за ед"].ToString()); field1.PriceRetailVAT = Convert.ToDouble(dr["Цена-1"].ToString()); field1.PriceRetailCurrency = Convert.ToDouble(dr["Цена-1"].ToString()); field1.PriceWholesaleVAT = Convert.ToDouble(dr["Цена-2"].ToString()); field1.PriceWholesaleCurrency = Convert.ToDouble(dr["Цена-2"].ToString()); field1.PriceIMVAT = Convert.ToDouble(dr["Цена-3"].ToString()); field1.PriceIMCurrency = Convert.ToDouble(dr["Цена-3"].ToString()); field1.DirCharColourID = ReturnDirCharColourID(dr["Поставщик"].ToString()); field1.DirCharTextureID = ReturnDirCharTextureID(dr["Примечание"].ToString()); alWrite.Add(field1); } else { //alCodeNot.Add(dr["Код товара"].ToString() + " - " + dr["Категория"].ToString() + " - " + dr["Товар"].ToString()); //... } } } //Create Purchase documents and Remnants of goods in stock docPurch = await Task.Run(() => DocsCreate(alWrite)); #region Чистим пустые партии товара, но только соотвутствующие Номеру документа, что бы НЕ удалить все пустые (0, 0) SQLiteParameter parDocID = new SQLiteParameter("@DocID", System.Data.DbType.Int32) { Value = docPurch.DocID }; await db.Database.ExecuteSqlCommandAsync("DELETE FROM RemParties WHERE DocID=@DocID and Remnant=0; ", parDocID); #endregion } ts.Commit(); } #endregion } OleDbConn.Close(); } } #endregion #region 5. Send dynamic collectionWrapper = new { Msg = "Файл загружен!" }; return Ok(returnServer.Return(true, collectionWrapper)); #endregion } catch (Exception ex) { try { OleDbConn.Close(); OleDbConn.Dispose(); } catch { } return Ok(returnServer.Return(false, exceptionEntry.Return(ex) + i777.ToString())); } #endregion }
// GET: api/DocSales public async Task <IHttpActionResult> GetDocSales(HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurchesReport")); if (iRight == 3) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); pID = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "pID", true) == 0).Value; pLanguage = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "pLanguage", true) == 0).Value); DateS = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DateS", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (DateS < Convert.ToDateTime("01.01.1800")) { DateS = Convert.ToDateTime(sysSetting.JurDateS.ToString("yyyy-MM-dd 00:00:00")).AddDays(-1); } else { DateS = DateS.AddDays(-1); } DatePo = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DatePo", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (DatePo < Convert.ToDateTime("01.01.1800")) { DatePo = Convert.ToDateTime(sysSetting.JurDatePo.ToString("yyyy-MM-dd 23:59:59")); } TypeRepair = false; bool bTypeRepair = Boolean.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "TypeRepair", true) == 0).Value, out TypeRepair); //TypeRepair DirContractorIDOrg = 0; bool bDirContractorIDOrg = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value, out DirContractorIDOrg); //DirContractorIDOrg DirContractorNameOrg = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorNameOrg", true) == 0).Value; //Request.Params["DirContractorNameOrg"]; DirWarehouseID = 0; bool bDirWarehouseID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value, out DirWarehouseID); //DirWarehouseID DirWarehouseName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseName", true) == 0).Value; //Request.Params["DirWarehouseName"]; DirServiceStatusID = 0; bool bDirServiceStatusID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value, out DirServiceStatusID); //DirServiceStatusID DirServiceStatusName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusName", true) == 0).Value; //Request.Params["DirServiceStatusName"]; DirEmployeeID = 0; bool bDirEmployeeID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeID", true) == 0).Value, out DirEmployeeID); //DirEmployeeID DirEmployeeName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeName", true) == 0).Value; //Request.Params["DirEmployeeName"]; DirEmployeeIDMaster = 0; bool bDirEmployeeIDMaster = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeIDMaster", true) == 0).Value, out DirEmployeeIDMaster); //DirEmployeeIDMaster DirEmployeeNameMaster = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeNameMaster", true) == 0).Value; //Request.Params["DirEmployeeNameMaster"]; DirServiceContractorID = 0; bool bDirServiceContractorID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceContractorID", true) == 0).Value, out DirServiceContractorID); //DirServiceContractorID DirServiceContractorName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceContractorName", true) == 0).Value; // Request.Params["DirServiceContractorName"]; ReportType = 0; bool bReportType = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ReportType", true) == 0).Value, out ReportType); //ReportType ReportTypeName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ReportTypeName", true) == 0).Value; // Request.Params["ReportTypeName"]; #endregion #region queryTemp var queryTemp = ( #region from from docServicePurches in db.DocServicePurches join dirServiceNomens11 in db.DirServiceNomens on docServicePurches.dirServiceNomen.Sub equals dirServiceNomens11.DirServiceNomenID into dirServiceNomens12 from dirServiceNomensSubGroup in dirServiceNomens12.DefaultIfEmpty() join dirServiceNomens21 in db.DirServiceNomens on dirServiceNomensSubGroup.Sub equals dirServiceNomens21.DirServiceNomenID into dirServiceNomens22 from dirServiceNomensGroup in dirServiceNomens22.DefaultIfEmpty() /* * join docServicePurch1Tabs1 in db.DocServicePurch1Tabs on docServicePurches.DocServicePurchID equals docServicePurch1Tabs1.DocServicePurchID into docServicePurch1Tabs2 * from docServicePurch1Tabs in docServicePurch1Tabs2.DefaultIfEmpty() * //where docServicePurch1Tabs.PriceCurrency > 0 */ /* * join docServicePurch2Tabs1 in db.DocServicePurch2Tabs on docServicePurches.DocServicePurchID equals docServicePurch2Tabs1.DocServicePurchID into docServicePurch2Tabs2 * from docServicePurch2Tabs in docServicePurch2Tabs2.DefaultIfEmpty() * //where docServicePurch2Tabs.PriceCurrency > 0 */ #endregion where docServicePurches.doc.DirContractorIDOrg == DirContractorIDOrg //&& docServicePurches.doc.DocDate >= DateS && docServicePurches.doc.DocDate <= DatePo #region group /* * group new { docServicePurch1Tabs, docServicePurch2Tabs } * //group new { docServicePurches } * by new * { * DocID = docServicePurches.DocID, * DocDate = docServicePurches.doc.DocDate, * Base = docServicePurches.doc.Base, * Held = docServicePurches.doc.Held, * Discount = docServicePurches.doc.Discount, * Del = docServicePurches.doc.Del, * Description = docServicePurches.doc.Description, * IsImport = docServicePurches.doc.IsImport, * DirVatValue = docServicePurches.doc.DirVatValue, * //DirPaymentTypeID = docServicePurches.doc.DirPaymentTypeID, * * //Принял * DirEmployeeID = docServicePurches.doc.DirEmployeeID, * DirEmployeeName = docServicePurches.doc.dirEmployee.DirEmployeeName, * //Мастер * DirEmployeeIDMaster = docServicePurches.DirEmployeeIDMaster, * DirEmployeeNameMaster = docServicePurches.dirEmployee.DirEmployeeName, * * DirServiceNomenID = docServicePurches.DirServiceNomenID, * //DirServiceNomenName = docServicePurches.dirServiceNomen.DirServiceNomenName, * DirServiceNomenName = * dirServiceNomensSubGroup.DirServiceNomenName == null ? docServicePurches.dirServiceNomen.DirServiceNomenName : * dirServiceNomensGroup.DirServiceNomenName == null ? dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName : * dirServiceNomensGroup.DirServiceNomenName + " / " + dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName, * * DocServicePurchID = docServicePurches.DocServicePurchID, * DirContractorName = docServicePurches.doc.dirContractor.DirContractorName, * DirContractorIDOrg = docServicePurches.doc.dirContractorOrg.DirContractorID, * DirContractorNameOrg = docServicePurches.doc.dirContractorOrg.DirContractorName, * DirWarehouseID = docServicePurches.dirWarehouse.DirWarehouseID, * DirWarehouseName = docServicePurches.dirWarehouse.DirWarehouseName, * * DirServiceStatusID = docServicePurches.DirServiceStatusID, * DirServiceStatusID_789 = docServicePurches.DirServiceStatusID_789, * SerialNumber = docServicePurches.SerialNumber, * TypeRepair = docServicePurches.TypeRepair, * ComponentDevice = docServicePurches.ComponentDevice, * * ComponentBattery = docServicePurches.ComponentBattery, * ComponentBatterySerial = docServicePurches.ComponentBatterySerial, * ComponentBackCover = docServicePurches.ComponentBackCover, * ComponentPasTextNo = docServicePurches.ComponentPasTextNo, * ComponentPasText = docServicePurches.ComponentPasText, * ComponentOtherText = docServicePurches.ComponentOtherText, * ProblemClientWords = docServicePurches.ProblemClientWords, * Note = docServicePurches.Note, * DirServiceContractorName = docServicePurches.DirServiceContractorName, * DirServiceContractorRegular = docServicePurches.DirServiceContractorRegular, * DirServiceContractorID = docServicePurches.DirServiceContractorID, * DirServiceContractorAddress = docServicePurches.DirServiceContractorAddress, * DirServiceContractorPhone = docServicePurches.DirServiceContractorPhone, * DirServiceContractorEmail = docServicePurches.DirServiceContractorEmail, * * PriceVAT = docServicePurches.PriceVAT, * //PriceCurrency = docServicePurches.PriceCurrency, * * DirCurrencyID = docServicePurches.DirCurrencyID, * DirCurrencyRate = docServicePurches.DirCurrencyRate, * DirCurrencyMultiplicity = docServicePurches.DirCurrencyMultiplicity, * DirCurrencyName = docServicePurches.dirCurrency.DirCurrencyName + " (" + docServicePurches.DirCurrencyRate + ", " + docServicePurches.DirCurrencyMultiplicity + ")", * * DateDone = docServicePurches.DateDone, * UrgentRepairs = docServicePurches.UrgentRepairs, * Prepayment = docServicePurches.Prepayment, * PrepaymentSum = docServicePurches.PrepaymentSum == null ? 0 : docServicePurches.PrepaymentSum, * * IssuanceDate = docServicePurches.IssuanceDate, * DateStatusChange = docServicePurches.DateStatusChange, * * //Оплата * Payment = docServicePurches.doc.Payment, * * //Сумма Выполненный работ + Запчастей * Sums = docServicePurches.Sums, * Sums1 = docServicePurches.Sums1, * Sums2 = docServicePurches.Sums2, * } * into g */ #endregion #region select docServicePurches select new { DocID = docServicePurches.DocID, DocDate = docServicePurches.doc.DocDate.ToString(), DocDate1 = docServicePurches.doc.DocDate, Base = docServicePurches.doc.Base, Held = docServicePurches.doc.Held, Del = docServicePurches.doc.Del, Description = docServicePurches.doc.Description, IsImport = docServicePurches.doc.IsImport, DirVatValue = docServicePurches.doc.DirVatValue, //DirPaymentTypeID = docServicePurches.DirPaymentTypeID, //DirPaymentTypeName = docServicePurches.DirPaymentTypeName, //Принял DirEmployeeID = docServicePurches.doc.DirEmployeeID, DirEmployeeName = docServicePurches.doc.dirEmployee.DirEmployeeName, //Мастер DirEmployeeIDMaster = docServicePurches.DirEmployeeIDMaster, DirEmployeeNameMaster = docServicePurches.dirEmployee.DirEmployeeName, DirServiceNomenID = docServicePurches.DirServiceNomenID, //DirServiceNomenName = docServicePurches.dirServiceNomen.DirServiceNomenName, DirServiceNomenName = dirServiceNomensSubGroup.DirServiceNomenName == null ? docServicePurches.dirServiceNomen.DirServiceNomenName : dirServiceNomensGroup.DirServiceNomenName == null ? dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName : dirServiceNomensGroup.DirServiceNomenName + " / " + dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName, DocServicePurchID = docServicePurches.DocServicePurchID, DirContractorName = docServicePurches.doc.dirContractor.DirContractorName, DirContractorIDOrg = docServicePurches.doc.dirContractorOrg.DirContractorID, DirContractorNameOrg = docServicePurches.doc.dirContractorOrg.DirContractorName, DirWarehouseID = docServicePurches.DirWarehouseID, DirWarehouseName = docServicePurches.dirWarehouse.DirWarehouseName, DirServiceStatusID = docServicePurches.DirServiceStatusID, DirServiceStatusID_789 = docServicePurches.DirServiceStatusID_789, SerialNumber = docServicePurches.SerialNumber, TypeRepair = docServicePurches.TypeRepair, ComponentDevice = docServicePurches.ComponentDevice, ComponentBattery = docServicePurches.ComponentBattery, ComponentBatterySerial = docServicePurches.ComponentBatterySerial, ComponentBackCover = docServicePurches.ComponentBackCover, ComponentPasTextNo = docServicePurches.ComponentPasTextNo, ComponentPasText = docServicePurches.ComponentPasText, ComponentOtherText = docServicePurches.ComponentOtherText, ProblemClientWords = docServicePurches.ProblemClientWords, Note = docServicePurches.Note, DirServiceContractorName = docServicePurches.DirServiceContractorName, DirServiceContractorRegular = docServicePurches.DirServiceContractorRegular, DirServiceContractorID = docServicePurches.DirServiceContractorID, DirServiceContractorAddress = docServicePurches.DirServiceContractorAddress, DirServiceContractorPhone = docServicePurches.DirServiceContractorPhone, DirServiceContractorEmail = docServicePurches.DirServiceContractorEmail, PriceVAT = docServicePurches.PriceVAT, //PriceCurrency = docServicePurches.PriceCurrency, DirCurrencyID = docServicePurches.DirCurrencyID, DirCurrencyRate = docServicePurches.DirCurrencyRate, DirCurrencyMultiplicity = docServicePurches.DirCurrencyMultiplicity, DirCurrencyName = docServicePurches.dirCurrency.DirCurrencyName + " (" + docServicePurches.DirCurrencyRate + ", " + docServicePurches.DirCurrencyMultiplicity + ")", DateDone = docServicePurches.DateDone.ToString(), DateDone1 = docServicePurches.DateDone, UrgentRepairs = docServicePurches.UrgentRepairs, Prepayment = docServicePurches.Prepayment, PrepaymentSum = docServicePurches.PrepaymentSum == null ? 0 : docServicePurches.PrepaymentSum, IssuanceDate = docServicePurches.IssuanceDate.ToString(), IssuanceDate1 = docServicePurches.IssuanceDate, DateStatusChange = docServicePurches.DateStatusChange.ToString(), DateStatusChange1 = docServicePurches.DateStatusChange, //Оплата Payment = docServicePurches.doc.Payment, /* * //1. Подсчет табличной части Работы "SumDocServicePurch1Tabs" * SumDocServicePurch1Tabs = g.Sum(x => x.docServicePurch1Tabs.PriceCurrency) == null ? 0 : Math.Round(g.Sum(x => x.docServicePurch1Tabs.PriceCurrency), sysSetting.FractionalPartInSum), * * //2. Подсчет табличной части Работы "SumDocServicePurch2Tabs" * SumDocServicePurch2Tabs = g.Sum(x => x.docServicePurch2Tabs.PriceCurrency) == null ? 0 : Math.Round(g.Sum(x => x.docServicePurch2Tabs.PriceCurrency), sysSetting.FractionalPartInSum), * * * //3. Сумма 1+2 "SumTotal" * SumTotal = * Math.Round( * (g.Sum(x => x.docServicePurch1Tabs.PriceCurrency) == null ? 0 : g.Sum(x => x.docServicePurch1Tabs.PriceCurrency)) + * (g.Sum(x => x.docServicePurch2Tabs.PriceCurrency) == null ? 0 : g.Sum(x => x.docServicePurch2Tabs.PriceCurrency)) * , sysSetting.FractionalPartInSum), * * //4. Константа "PrepaymentSum" * //... * * //5. 3 - 4 "SumTotal2" * SumTotal2 = g.Key.Sums, */ DiscountX = docServicePurches.DiscountX, SumDocServicePurch1Tabs = docServicePurches.Sums1, DiscountY = docServicePurches.DiscountY, SumDocServicePurch2Tabs = docServicePurches.Sums2, SumTotal = (docServicePurches.Sums1 - docServicePurches.DiscountX) + (docServicePurches.Sums2 - docServicePurches.DiscountY), SumTotal2 = docServicePurches.Sums - docServicePurches.DiscountX - docServicePurches.DiscountY, } #endregion ); if (DirWarehouseID > 0) { queryTemp = queryTemp.Where(z => z.DirWarehouseID == DirWarehouseID); } if (DirServiceStatusID > 0) { queryTemp = queryTemp.Where(z => z.DirServiceStatusID == DirServiceStatusID); } if (DirEmployeeID > 0) { queryTemp = queryTemp.Where(z => z.DirEmployeeID == DirEmployeeID); } if (DirEmployeeIDMaster > 0) { queryTemp = queryTemp.Where(z => z.DirEmployeeIDMaster == DirEmployeeIDMaster); } if (DirServiceContractorID > 0) { queryTemp = queryTemp.Where(z => z.DirServiceContractorID == DirServiceContractorID); } if (ReportType > 0) { switch (ReportType) { //1. Выданные (все) case 1: { queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo)); } break; //2. Выданные (готовые) case 2: { queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && z.DirServiceStatusID_789 == 7 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo)); } break; //3. Не отремонтированные все (Выданные (отказные)) case 3: { queryTemp = queryTemp.Where(z => z.DirServiceStatusID_789 == 8 && (z.IssuanceDate1 >= DateS && z.IssuanceDate1 <= DatePo)); //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && z.DirServiceStatusID_789 == 8 && (z.DocDate >= DateS && z.DocDate <= DatePo)); } break; //4. Сделанные case 4: { queryTemp = queryTemp.Where(z => z.DirServiceStatusID_789 == 7 && (z.IssuanceDate1 >= DateS && z.IssuanceDate1 <= DatePo)); //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 7 && (z.DocDate >= DateS && z.DocDate <= DatePo)); } break; //5. Принятые case 5: { queryTemp = queryTemp.Where(z => (z.DocDate1 >= DateS && z.DocDate1 <= DatePo)); //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 1 && (z.DocDate >= DateS && z.DocDate <= DatePo)); } break; default: { queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo)); } break; } } else { queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo)); } #endregion #region Отправка JSON int dirCount = queryTemp.Count(); dynamic collectionWrapper1 = new { sucess = true, total = dirCount, DocServicePurchesReport = queryTemp }; return(await Task.Run(() => Ok(collectionWrapper1))); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
// GET: api/DocSecondHandInvs public async Task <IHttpActionResult> GetTimerController(HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) //int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSecondHandInventories")); //if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры Params _params = new Params(); //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); #endregion #region Основной запрос *** *** *** var queryDocSecondHandInv = ( from x in db.DocSecondHandInvs where x.DirEmployee2ID == field.DirEmployeeID && x.DirEmployee1Podpis == true && x.DirEmployee2Podpis != true && x.doc.Held != true select new { x.doc.DocID, x.doc.DocDate, x.DocSecondHandInvID, x.dirWarehouse.DirWarehouseName } ); #endregion #region Отправка JSON dynamic collectionWrapper = new { sucess = true, DocSecondHandInv = queryDocSecondHandInv }; return(await Task.Run(() => Ok(collectionWrapper))); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> PutSms(int id, DirSmsTemplate dirSmsTemplate, HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права /*int Status = await Task.Run(() => accessRight.Access(db, field.DirEmployeeID, "DirBank")); * if (Status >= 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));*/ //Права (1 - Write, 2 - Read, 3 - No Access) //int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirBanks")); //if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))); //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); //Параметры int ListObjectID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ListObjectID", true) == 0).Value); //Записей на страницу #endregion #region Проверки //Активны SMS if (!sysSetting.SmsActive) { return(Ok(returnServer.Return(false, "Активируйте в Настройках (верхнее меню) оповещение по SMS!"))); } string Phone = ""; if (ListObjectID == 40) { //Находим по "DocServicePurchID" номер телефона клиента Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(id); // DirServiceContractorPhone == "79257711344" //Проверка номера телефона if (docServicePurch.DirServiceContractorPhone == null) { return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!"))); } //Убираем + в самом начале docServicePurch.DirServiceContractorPhone = docServicePurch.DirServiceContractorPhone.Replace("+", ""); //Проверка номера телефона if (docServicePurch.DirServiceContractorPhone.Length < 11) { return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!"))); } Phone = docServicePurch.DirServiceContractorPhone; } else if (ListObjectID == 33) { //Находим по "DocMovementID" документ Models.Sklad.Doc.DocMovement docMovement = await db.DocMovements.FindAsync(id); // DirServiceContractorPhone == "79257711344" //По документу находим курьера и его номер телефона Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(docMovement.DirEmployeeIDCourier); //Проверка номера телефона if (dirEmployee.Phone == null) { return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!"))); } //Убираем + в самом начале dirEmployee.Phone = dirEmployee.Phone.Replace("+", ""); //Проверка номера телефона if (dirEmployee.Phone.Length < 11) { return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!"))); } Phone = dirEmployee.Phone; } #endregion #region OLD /* * * string res = ""; * * if (sysSetting.SmsServiceID == 1) * { #region sms48_ru * * //Отправка SMS * PartionnyAccount.Classes.SMS.sms48_ru sms48_ru = new Classes.SMS.sms48_ru(); * res = sms48_ru.Send(sysSetting, Phone, dirSmsTemplate.DirSmsTemplateMsg); * * //Результат * if (res == "8") res = "Отправлено"; * else if (res == "1") res = "Доставлено"; * else if (res == "2") res = "Не удалось"; * else res = "Ошибка: " + res; * * //Пишем в Лог * await RecordInLog(ListObjectID, id, "Номер тел.:" + Phone + "Текст SMS: " + dirSmsTemplate.DirSmsTemplateMsg + "<br /> Результат: " + res, field); * #endregion * } * else if (sysSetting.SmsServiceID == 2) * { #region sms4b_ru - не работает * #endregion * } * if (sysSetting.SmsServiceID == 3) * { #region infobip_com * * //Отправка SMS * PartionnyAccount.Classes.SMS.infobip_com infobip_com = new Classes.SMS.infobip_com(); * res = infobip_com.Send(sysSetting, Phone, dirSmsTemplate.DirSmsTemplateMsg); * * //Пишем в Лог * await RecordInLog(ListObjectID, id, "Номер тел.:" + Phone + "Текст SMS: " + dirSmsTemplate.DirSmsTemplateMsg + "<br /> Результат: " + res, field); * #endregion * } */ #endregion int DocID = 0; string res = await SenSms( //res, sysSetting, ListObjectID, id, Phone, dirSmsTemplate.DirSmsTemplateMsg, field, db, id ); #region Меняем в таблице "DocServicePurches" поля: "AlertedCount" и "AlertedDate" PartionnyAccount.Models.Sklad.Doc.DocServicePurch docServicePurch1 = await db.DocServicePurches.FindAsync(id); docServicePurch1.AlertedCount = Convert.ToInt32(docServicePurch1.AlertedCount) + 1; docServicePurch1.AlertedDateTxt = DateTime.Now.ToString("yyyy-MM-dd"); docServicePurch1.AlertedDate = DateTime.Now; db.Entry(docServicePurch1).State = EntityState.Modified; await db.SaveChangesAsync(); #endregion dynamic collectionWrapper = new { Msg = res }; return(Ok(returnServer.Return(true, collectionWrapper))); } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
public async Task <IHttpActionResult> DeleteDirEmployee(int id) { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirEmployees")); if (iRight != 1) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Удаление try { //История Сотрудника var query = await ( from x in db.DirEmployeeHistories where x.DirEmployeeID == id select x ).ToListAsync(); //Сотрудник Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(id); if (dirEmployee == null) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99))); } if (dirEmployee.SysRecord) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg98))); } if (!dirEmployee.Del) { // === Удаляем === === === === === #region 6. JourDisp *** *** *** *** *** *** *** *** *** * Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp(); sysJourDisp.DirDispOperationID = 5; //Удаление записи sysJourDisp.DirEmployeeID = field.DirEmployeeID; sysJourDisp.ListObjectID = ListObjectID; sysJourDisp.TableFieldID = dirEmployee.DirEmployeeID; sysJourDisp.Description = ""; try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { } #endregion using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction()) { //1. Сотрудника try { //1. Историю Сотрудника for (int i = 0; i < query.Count(); i++) { Models.Sklad.Dir.DirEmployeeHistory dirEmployeeHistory = await db.DirEmployeeHistories.FindAsync(query[i].DirEmployeeHistoryID); db.DirEmployeeHistories.Remove(dirEmployeeHistory); await db.SaveChangesAsync(); } db.DirEmployees.Remove(dirEmployee); await db.SaveChangesAsync(); ts.Commit(); dynamic collectionWrapper = new { ID = dirEmployee.DirEmployeeID, Msg = Classes.Language.Sklad.Language.msg19 }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); } catch (Exception ex) { ts.Rollback(); if (function.ExceptionFkExist(ex)) { //2. Исключение - пометка на удаление dirEmployee.Del = true; db.Entry(dirEmployee).State = EntityState.Modified; await db.SaveChangesAsync(); dynamic collectionWrapper = new { ID = dirEmployee.DirEmployeeID, Msg = Classes.Language.Sklad.Language.msg96 //"Помечено на удаление, так как запись задействована в других объектах сервиса (напр. в документах)." }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); } else { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } } //catch } //DbContextTransaction } else { // === Снимаем пометку на удаление === === === === === dirEmployee.Del = false; db.Entry(dirEmployee).State = EntityState.Modified; await db.SaveChangesAsync(); dynamic collectionWrapper = new { ID = dirEmployee.DirEmployeeID, Msg = Classes.Language.Sklad.Language.msg97 //"Пометка на удаление снята." }; return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")); } } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } #endregion }
// GET: api/DocSalaries public async Task <IHttpActionResult> GetDocSalaries(HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocSalaries")); if (iRight == 3) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры Params _params = new Params(); //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); //Параметры _params.limit = sysSetting.PageSizeJurn; //Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "limit", true) == 0).Value); //Записей на страницу _params.page = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "page", true) == 0).Value); //Номер страницы _params.Skip = _params.limit * (_params.page - 1); _params.GroupID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "pGroupID", true) == 0).Value); //Кликнули по группе _params.parSearch = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "parSearch", true) == 0).Value; if (_params.parSearch != null) { _params.parSearch = _params.parSearch.ToLower(); //Поиск } _params.FilterType = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "FilterType", true) == 0).Value); _params.DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value); _params.DateS = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DateS", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (_params.DateS < Convert.ToDateTime("01.01.1800")) { _params.DateS = Convert.ToDateTime(sysSetting.JurDateS.ToString("yyyy-MM-dd 00:00:00")).AddDays(-1); } else { _params.DateS = _params.DateS.Value.AddDays(-1); } _params.DatePo = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DatePo", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (_params.DatePo < Convert.ToDateTime("01.01.1800")) { _params.DatePo = Convert.ToDateTime(sysSetting.JurDatePo.ToString("yyyy-MM-dd 23:59:59")); } #endregion #region Основной запрос *** *** *** var query = ( from docSalaries in db.DocSalaries join docSalaryTabs1 in db.DocSalaryTabs on docSalaries.DocSalaryID equals docSalaryTabs1.DocSalaryID into docSalaryTabs2 from docSalaryTabs in docSalaryTabs2.DefaultIfEmpty() where docSalaries.doc.DocDate >= _params.DateS && docSalaries.doc.DocDate <= _params.DatePo group new { docSalaryTabs } by new { DocID = docSalaries.DocID, DocDate = docSalaries.doc.DocDate, DocYear = docSalaries.DocYear, DocMonth = docSalaries.DocMonth, Base = docSalaries.doc.Base, Held = docSalaries.doc.Held, Discount = docSalaries.doc.Discount, Del = docSalaries.doc.Del, Description = docSalaries.doc.Description, DocSalaryID = docSalaries.DocSalaryID, DirContractorIDOrg = docSalaries.doc.dirContractorOrg.DirContractorID, DirContractorNameOrg = docSalaries.doc.dirContractorOrg.DirContractorName, } into g select new { DocID = g.Key.DocID, DocDate = g.Key.DocDate, Held = g.Key.Held, Base = g.Key.Base, Del = g.Key.Del, Description = g.Key.Description, DocSalaryID = g.Key.DocSalaryID, DirContractorIDOrg = g.Key.DirContractorIDOrg, DirContractorNameOrg = g.Key.DirContractorNameOrg, //1. SumSalary = g.Sum(x => x.docSalaryTabs.SumSalary) == null ? 0 : g.Sum(x => x.docSalaryTabs.SumSalary), //2. DirBonusIDSalary = g.Sum(x => x.docSalaryTabs.DirBonusIDSalary) == null ? 0 : g.Sum(x => x.docSalaryTabs.DirBonusIDSalary), //3. DirBonus2IDSalary = g.Sum(x => x.docSalaryTabs.DirBonus2IDSalary) == null ? 0 : g.Sum(x => x.docSalaryTabs.DirBonus2IDSalary), //4. Sums = g.Sum(x => x.docSalaryTabs.Sums) == null ? 0 : g.Sum(x => x.docSalaryTabs.Sums), } ); #endregion #region Условия (параметры) *** *** *** #region dirEmployee.DirContractorIDOrg if (dirEmployee.DirContractorIDOrg != null && dirEmployee.DirContractorIDOrg > 0) { query = query.Where(x => x.DirContractorIDOrg == dirEmployee.DirContractorIDOrg); } #endregion #region Не показывать удалённые if (!Convert.ToBoolean(sysSetting.DeletedRecordsShow)) { query = query.Where(x => x.Del == sysSetting.DeletedRecordsShow); } #endregion #region Фильтр if (_params.FilterType > 0) { switch (_params.FilterType) { case 1: query = query.Where(x => x.Held == true); break; case 2: query = query.Where(x => x.Held == false); break; } } #endregion #region Поиск if (!String.IsNullOrEmpty(_params.parSearch)) { //Проверяем число ли это Int32 iNumber32; bool bResult32 = Int32.TryParse(_params.parSearch, out iNumber32); DateTime dDateTime; bool bDateTime = DateTime.TryParse(_params.parSearch, out dDateTime); //Если число, то задействуем в поиске и числовые поля (_params.parSearch == iNumber) if (bResult32) { query = query.Where(x => x.DocSalaryID == iNumber32); } //Если Дата else if (bDateTime) { query = query.Where(x => x.DocDate == dDateTime); } //Иначе, только текстовые поля else { //query = query.Where(x => x.DirContractorName.Contains(_params.parSearch) || x.DirWarehouseName.Contains(_params.parSearch) || x.NumberInt.Contains(_params.parSearch) || x.NumberTT.Contains(_params.parSearch)); } } #endregion #region OrderBy и Лимит query = query.OrderByDescending(x => x.DocDate).Skip(_params.Skip).Take(_params.limit); #endregion #endregion #region Отправка JSON //К-во Номенклатуры int dirCount = await Task.Run(() => db.DocSalaries.Where(x => x.doc.DocDate >= _params.DateS && x.doc.DocDate <= _params.DatePo).Count()); //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное! int dirCount2 = query.Count(); if (dirCount2 < _params.limit) { dirCount = _params.limit * (_params.page - 1) + dirCount2; } dynamic collectionWrapper = new { sucess = true, total = dirCount, DocSalary = query }; return(await Task.Run(() => Ok(collectionWrapper))); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
private Field Comercial(string DirEmployeeLogin, string DirEmployeePswd, bool bEncode) { Function.Variables.ConnectionString connectionString = new Function.Variables.ConnectionString(); Field field = new Field(); #region Проверяем "IsNullOrEmpty" if (String.IsNullOrEmpty(DirEmployeeLogin) && String.IsNullOrEmpty(DirEmployeePswd)) { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg4; return(field); } #endregion #region Декодируем Логин и Пароль if (bEncode) { Account.EncodeDecode encode = new Account.EncodeDecode(); DirEmployeeLogin = encode.UnionDecode(DirEmployeeLogin); field.LoginFull = DirEmployeeLogin; DirEmployeePswd = encode.UnionDecode(DirEmployeePswd); } #endregion #region азщепляем Логин на 2-е составные части Логин@МояКомпания if (DirEmployeeLogin.IndexOf("@") == -1) { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg26; return(field); } else { string _Login = DirEmployeeLogin; int p1 = _Login.IndexOf("@"); DirEmployeeLogin = _Login; DirEmployeeLogin = DirEmployeeLogin.Remove(p1, DirEmployeeLogin.Length - p1); field.Login = _Login.Remove(0, p1 + 1); } #endregion #region Получаем DirCustomersID (из MS SQL) //Получаем ID-шник в БД MS SQL field.DirCustomersID = connectionString.mDirCustomersID(field.Login); //Полученные варианты if (field.DirCustomersID == -1) //Не найден такой User. { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg1 + DirEmployeeLogin; return(field); } else if (field.DirCustomersID == 0) //Найден такой User, но не активен (долго не заходил в свой аккаунт) { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg2(); return(field); } #endregion #region Проверяем Логин и Пароль //using (DbConnectionSklad db = new DbConnectionSklad(GetSQLiteBasicConnStr_DirCustomersID(field.DirCustomersID))) using (DbConnectionSklad db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true))) { db.Database.Connection.Open(); var query = db.DirEmployees.Where(x => x.DirEmployeeLogin == DirEmployeeLogin && x.DirEmployeePswd == DirEmployeePswd && x.Del == false && x.DirEmployeeActive == true).ToList(); if (query.Count > 0) { Models.Sklad.Dir.DirEmployee dirEmployee = query[0]; field.Access = true; field.DirEmployeeID = Convert.ToInt32(dirEmployee.DirEmployeeID); //field.SysDirRightsID = dirEmployee.SysDirRightsID; //field.RetailOnly = Convert.ToBoolean(dirEmployee.RetailOnly); } else { field.Access = false; field.Msg = Classes.Language.Sklad.Language.msg4; return(field); } } #endregion return(field); }
private void Copy_Folder_DBFile(int DirCustomersID) { //Class.Settings.Variables _var = new Class.Settings.Variables(); Classes.Function.Variables.ConnectionString connectionString = new Function.Variables.ConnectionString(); //1.Создание папок в Users\ // user_XXX // user_XXX\Base // user_XXX\File if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID)) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID); } if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\Base")) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\Base"); } if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File")) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File"); } if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Logo")) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Logo"); } if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Photo")) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Photo"); } if (!Directory.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Export")) { Directory.CreateDirectory(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\File\Export"); } //2.Копирование БД из 'Users\Etalon\Base\basic.db' в 'Users\user_XXX\Base\basic.db' if (!File.Exists(connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\Base\basic.db")) { File.Copy(connectionString.SQLitePathEtalon(), connectionString.SQLitePathUser() + @"\user_" + DirCustomersID + @"\Base\basic.db"); } /* * using (SQLiteConnection con = new SQLiteConnection(connectionString.GetSQLiteBasicConnStr_DirCustomersID(DirCustomersID))) * { * using (SQLiteCommand cmd = new SQLiteCommand("UPDATE DirEmployees SET DirEmployeePswd=@DirEmployeePswd", con)) * { * SQLiteParameter parDirEmployeePswd = new SQLiteParameter("@DirEmployeePswd", System.Data.DbType.String) { Value = pPswd }; cmd.Parameters.Add(parDirEmployeePswd); * con.Open(); cmd.ExecuteNonQuery(); con.Close(); con.Dispose(); * } * } */ //2.1.Меняем пароль Администратору using (DbConnectionSklad db = new DbConnectionSklad(connectionString.Return(DirCustomersID, null, true))) { Models.Sklad.Dir.DirEmployee dirEmployee = db.DirEmployees.Where(x => x.DirEmployeeID == 1).ToList()[0]; dirEmployee.DirEmployeePswd = pPswd; db.Entry(dirEmployee).State = EntityState.Modified; db.SaveChanges(); } //3.Для файлов Users/user_x (например изображения) if (!Directory.Exists(connectionString.FilePathUser() + @"\user_" + DirCustomersID)) { Directory.CreateDirectory(connectionString.FilePathUser() + @"\user_" + DirCustomersID); } }
// GET: api/DocSales public async Task <IHttpActionResult> GetDocSales(HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); dbRead = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightReportLogistics")); if (iRight == 3) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID); #endregion #region Параметры //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); DateS = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DateS", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (DateS < Convert.ToDateTime("01.01.1800")) { DateS = Convert.ToDateTime(sysSetting.JurDateS.ToString("yyyy-MM-dd 00:00:00")).AddDays(-1); } else { DateS = DateS.AddDays(-1); } DatePo = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DatePo", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (DatePo < Convert.ToDateTime("01.01.1800")) { DatePo = Convert.ToDateTime(sysSetting.JurDatePo.ToString("yyyy-MM-dd 23:59:59")); } DirContractorIDOrg = 0; bool bDirContractorIDOrg = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value, out DirContractorIDOrg); DirContractorNameOrg = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorNameOrg", true) == 0).Value; DirEmployeeID = 0; bool bDirEmployeeID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeID", true) == 0).Value, out DirEmployeeID); DirEmployeeName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeName", true) == 0).Value; DirMovementStatusID = 0; bool bDirMovementStatusID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirMovementStatusID", true) == 0).Value, out DirMovementStatusID); DirMovementStatusName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirMovementStatusName", true) == 0).Value; DocOrTab = 1; bool bDocOrTab = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocOrTab", true) == 0).Value, out DocOrTab); #endregion if (DocOrTab == 1) { #region query var queryTemp = ( from docMovements in db.DocMovements where docMovements.doc.DocDate >= DateS && docMovements.doc.DocDate <= DatePo && docMovements.DirMovementStatusID > 1 select new { //№ DocMovementID = docMovements.DocMovementID, //Дата DocDate = docMovements.doc.DocDate, //Точка - откуда DirWarehouseIDFrom = docMovements.DirWarehouseIDFrom, DirWarehouseNameFrom = docMovements.dirWarehouseFrom.DirWarehouseName, //Курьер DirEmployeeIDCourier = docMovements.DirEmployeeIDCourier, DirEmployeeNameCourier = docMovements.dirEmployee_Courier.DirEmployeeName, //Курьер DirWarehouseIDTo = docMovements.DirWarehouseIDTo, DirWarehouseNameTo = docMovements.dirWarehouseTo.DirWarehouseName, DirMovementStatusID = docMovements.DirMovementStatusID, DirMovementStatusName = docMovements.dirMovementStatus.DirMovementStatusName, } ); if (DirEmployeeID > 0) { queryTemp = queryTemp.Where(z => z.DirEmployeeIDCourier == DirEmployeeID); } if (DirMovementStatusID > 0) { queryTemp = queryTemp.Where(z => z.DirMovementStatusID == DirMovementStatusID); } else { queryTemp = queryTemp.Where(z => z.DirMovementStatusID <= 3); } #endregion #region Отправка JSON int dirCount = queryTemp.Count(); dynamic collectionWrapper1 = new { sucess = true, total = dirCount, ReportLogistics = queryTemp }; return(await Task.Run(() => Ok(collectionWrapper1))); #endregion } else { #region query var queryTemp = ( from docMovements in db.DocMovements from docMovementTabs in db.DocMovementTabs join dirNomens11 in db.DirNomens on docMovementTabs.dirNomen.Sub equals dirNomens11.DirNomenID into dirNomens12 from dirNomensSubGroup in dirNomens12.DefaultIfEmpty() join dirNomens21 in db.DirNomens on dirNomensSubGroup.Sub equals dirNomens21.DirNomenID into dirNomens22 from dirNomensGroup in dirNomens22.DefaultIfEmpty() #region Характеристики join dirCharColours1 in db.DirCharColours on docMovementTabs.DirCharColourID equals dirCharColours1.DirCharColourID into dirCharColours2 from dirCharColours in dirCharColours2.DefaultIfEmpty() join dirCharMaterials1 in db.DirCharMaterials on docMovementTabs.DirCharMaterialID equals dirCharMaterials1.DirCharMaterialID into dirCharMaterials2 from dirCharMaterials in dirCharMaterials2.DefaultIfEmpty() join dirCharNames1 in db.DirCharNames on docMovementTabs.DirCharNameID equals dirCharNames1.DirCharNameID into dirCharNames2 from dirCharNames in dirCharNames2.DefaultIfEmpty() join dirCharSeasons1 in db.DirCharSeasons on docMovementTabs.DirCharSeasonID equals dirCharSeasons1.DirCharSeasonID into dirCharSeasons2 from dirCharSeasons in dirCharSeasons2.DefaultIfEmpty() join dirCharSexes1 in db.DirCharSexes on docMovementTabs.DirCharSexID equals dirCharSexes1.DirCharSexID into dirCharSexes2 from dirCharSexes in dirCharSexes2.DefaultIfEmpty() join dirCharSizes1 in db.DirCharSizes on docMovementTabs.DirCharSizeID equals dirCharSizes1.DirCharSizeID into dirCharSizes2 from dirCharSizes in dirCharSizes2.DefaultIfEmpty() join dirCharStyles1 in db.DirCharStyles on docMovementTabs.DirCharStyleID equals dirCharStyles1.DirCharStyleID into dirCharStyles2 from dirCharStyles in dirCharStyles2.DefaultIfEmpty() join dirCharTextures1 in db.DirCharTextures on docMovementTabs.DirCharTextureID equals dirCharTextures1.DirCharTextureID into dirCharTextures2 from dirCharTextures in dirCharTextures2.DefaultIfEmpty() #endregion where docMovements.DocMovementID == docMovementTabs.DocMovementID && docMovements.doc.DocDate >= DateS && docMovements.doc.DocDate <= DatePo && docMovements.DirMovementStatusID > 1 select new { DocMovementID = docMovements.DocMovementID, //Код товара DirNomenID = docMovementTabs.DirNomenID, Sub = docMovementTabs.dirNomen.Sub, //Товар Наименование DirNomenName = docMovementTabs.dirNomen.DirNomenName, DirNomenPatchFull = dirNomensSubGroup.DirNomenName == null ? "" : dirNomensGroup.DirNomenName == null ? dirNomensSubGroup.DirNomenName : dirNomensGroup.DirNomenName + " / " + dirNomensSubGroup.DirNomenName, //К-во Sale_Quantity = docMovementTabs.Quantity, DocDate = docMovements.doc.DocDate, //Точка - откуда DirWarehouseIDFrom = docMovements.DirWarehouseIDFrom, DirWarehouseNameFrom = docMovements.dirWarehouseFrom.DirWarehouseName, //Курьер DirEmployeeIDCourier = docMovements.DirEmployeeIDCourier, DirEmployeeNameCourier = docMovements.dirEmployee_Courier.DirEmployeeName, //Курьер DirWarehouseIDTo = docMovements.DirWarehouseIDTo, DirWarehouseNameTo = docMovements.dirWarehouseTo.DirWarehouseName, DirMovementStatusID = docMovements.DirMovementStatusID, DirMovementStatusName = docMovements.dirMovementStatus.DirMovementStatusName, //Характеристики /* * DirCharColourName = dirCharColours.DirCharColourName, * DirCharMaterialName = dirCharMaterials.DirCharMaterialName, * DirCharNameName = dirCharNames.DirCharNameName, * DirCharSeasonName = dirCharSeasons.DirCharSeasonName, * DirCharSexName = dirCharSexes.DirCharSexName, * DirCharSizeName = dirCharSizes.DirCharSizeName, * DirCharStyleName = dirCharStyles.DirCharStyleName, * DirCharTextureName = dirCharTextures.DirCharTextureName, */ DirChar = dirCharColours.DirCharColourName + " " + dirCharMaterials.DirCharMaterialName + " " + dirCharNames.DirCharNameName + " " + dirCharSeasons.DirCharSeasonName + " " + dirCharSexes.DirCharSexName + " " + dirCharSizes.DirCharSizeName + " " + dirCharStyles.DirCharStyleName + " " + dirCharTextures.DirCharTextureName, //SerialNumber = docMovementTabs.SerialNumber, //Barcode = docMovementTabs.Barcode, } ); if (DirEmployeeID > 0) { queryTemp = queryTemp.Where(z => z.DirEmployeeIDCourier == DirEmployeeID); } if (DirMovementStatusID > 0) { queryTemp = queryTemp.Where(z => z.DirMovementStatusID == DirMovementStatusID); } else { queryTemp = queryTemp.Where(z => z.DirMovementStatusID <= 3); } #endregion #region Отправка JSON int dirCount = queryTemp.Count(); dynamic collectionWrapper1 = new { sucess = true, total = dirCount, ReportLogistics = queryTemp }; return(await Task.Run(() => Ok(collectionWrapper1))); #endregion } } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }