Beispiel #1
0
        public ActionResult _InsertPerson(int workerWorkplaceId, int StorageNameId)
        {
            Organization    currentOrg = organizationRepository.Get(getIntCurrentEnterpriseId());
            WorkerWorkplace wp         = workerWorkplaceRepository.Get(workerWorkplaceId);

            if (wp != null && wp.RootOrganization == currentOrg.Id)
            {
                StorageName currentStorageName          = storageNameRepository.Get(StorageNameId);
                Dictionary <string, object> queryParams = new Dictionary <string, object>();
                queryParams.Add("Organization", currentOrg);
                queryParams.Add("Worker", wp.Worker);
                queryParams.Add("StorageName", currentStorageName);
                MatPersonCardHead person = matPersonCardHeadRepository.FindOne(queryParams);
                if (person == null)
                {
                    person = new MatPersonCardHead();
                    person.Organization = currentOrg;
                    person.Worker       = wp.Worker;
                }

                /*
                 * if (person.StorageName != currentStorageName)
                 *  ModelState.AddModelError("","Этот сотрудник уже числится на складе: " + currentStorageName.Name);
                 * else
                 * {*/
                person.IsActive    = true;
                person.Department  = wp.Organization.Parent;
                person.StorageName = currentStorageName;
                matPersonCardHeadRepository.SaveOrUpdate(person);
                //}
            }
            return(View(new GridModel(new List <MatPersonCardHead>())));
        }
Beispiel #2
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Taint != null ? Taint.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (StorageName != null ? StorageName.GetHashCode() : 0);
         return(hashCode);
     }
 }
Beispiel #3
0
        public static StorageName rebuildStorageName(StorageName inStorageName, List <string> excludeProperty)
        {
            StorageName sn = null;

            if (inStorageName != null)
            {
                sn               = new StorageName(inStorageName.Id);
                sn.Name          = inStorageName.Name;
                sn.StorageNumber = inStorageName.StorageNumber;
            }
            return(sn);
        }
Beispiel #4
0
        private void OnStorageChanged(string storageName, SecurityIdMapping mapping)
        {
            if (!StorageName.CompareIgnoreCase(storageName))
            {
                return;
            }

            // if adapter code is empty means mapping removed
            // also mapping can be changed (new adapter code for old security code)

            lock (_syncRoot)
            {
                _securityIds.RemoveByValue(mapping.StockSharpId);
                _securityIds.Add(mapping.StockSharpId, mapping.AdapterId);
            }
        }
        private void OnStorageNewIdentifierAdded(string storageName, SecurityId securityId, object nativeId)
        {
            if (!StorageName.CompareIgnoreCase(storageName))
            {
                return;
            }

            bool added;

            lock (_syncRoot)
                added = _securityIds.TryAdd(nativeId, securityId);

            if (added)
            {
                var temp = securityId;
                temp.Native = nativeId;
                RaiseNewOutMessage(new ProcessSuspendedSecurityMessage(this, temp));
            }
        }
        public ActionResult Select(int?workerWorkplaceId, string workerWorkplaceText, string storageNameId)
        {
            IList <WorkerNorma> workerNormas = new List <WorkerNorma>();
            WorkerNorma         workerNorma  = null;

            // Убрали запоминание табельных. Кладовщики путаются
            //if (workerWorkplaceId == null && Session["workerWorkplaceId"] != null)
            //    workerWorkplaceId = (int)Session["workerWorkplaceId"];
            if (workerWorkplaceId != null)
            {
                WorkerWorkplace workerWorkplace = workerWorkplaceRepository.Get(workerWorkplaceId.Value);
                //ViewData["worker"] = workerWorkplace.Worker;


                Session.Add("workerWorkplaceId", workerWorkplaceId);
                Session.Add("workerWorkplaceText", workerWorkplaceText);
                Session.Add("storageNameId", storageNameId);


                Dictionary <string, object> query = new Dictionary <string, object>();
                Dictionary <string, object> order = new Dictionary <string, object>();
                query.Add("WorkerWorkplace", workerWorkplace);
                WorkerCardHead workerCardHead = workerCardRepository.FindOne(query);

                if (workerCardHead != null)
                {
                    //query.Clear();
                    //order.Clear();
                    //query.Add("WorkerCardHead.Id", workerCardHead.Id);
                    //order.Add("Storage.Nomenclature.Name", ASC);
                    //workerCardHead.WorkerCardContents = workerCardContentRepository.GetByCriteria(query, order);
                    workerCardHead.WorkerCardContents = reorderWorkerCardContents(workerCardHead.WorkerCardContents);

                    foreach (WorkerCardContent workerCardContent in workerCardHead.WorkerCardContents)
                    {
                        //if (workerCardContent.Quantity <= 0)
                        //    continue;
                        StorageName storageName = storageNameRepository.Get(int.Parse(storageNameId));
//                        if (workerCardContent.Storage.StorageName.Id.ToString() != storageNameId)
                        if (workerCardContent.Storage.StorageName.StorageNumber != storageName.StorageNumber)
                        {
                            continue;
                        }
                        if (workerCardContent.Quantity > 0)
                        {
                            workerNorma = new WorkerNorma();
                            //workerNorma.Storage = rebuildStorage(workerCardContent.Storage);
                            workerNorma.Id            = workerCardContent.Id;
                            workerNorma.StorageId     = workerCardContent.Storage.Id;
                            workerNorma.StorageNumber = workerCardContent.Storage.StorageName.StorageNumber;
                            workerNorma.StorageInfo   = workerCardContent.Storage.StorageInfo;
                            workerNorma.Wear          = workerCardContent.Storage.Wear;
                            //Возвращают в основном б/у
                            //workerNorma.Wear = "50";
                            workerNorma.Wear = "";
//                            workerNorma.ReceptionDate = workerCardContent.Operation.OperDate;
                            workerNorma.ReceptionDate   = workerCardContent.StartDate;
                            workerNorma.PresentQuantity = workerCardContent.Quantity;
                            //workerNorma.PutQuantity = workerNorma.PresentQuantity;
                            workerNorma.PutQuantity = 0;
                            workerNormas.Add(workerNorma);
                        }
                    }
                }
            }
            return(View(new GridModel(workerNormas)));
        }
        public List <COMING_SAP> GetInvoice(Organization currentOrganization, StorageName currentStorage, ICriteriaRepository <Nomenclature> nomenRepository, ICriteriaRepository <NomGroup> nomGroupRepository,
                                            int DocTypeId, string docNumber, int docYear, string docDate, out string Message)
        {
            List <COMING_SAP>           model   = new List <COMING_SAP>();
            IFormatProvider             culture = new System.Globalization.CultureInfo("ru-RU", true);
            Dictionary <string, Object> param   = new Dictionary <string, Object>();

            Message = "OK";
            string        paramPrefix  = DbPapamPrefix;
            int           rowCount     = 0;
            IDbConnection dbConnection = this.Session.Connection;

            if (dbConnection.State == ConnectionState.Closed)
            {
                dbConnection.Open();
            }
            using (var cmd = dbConnection.CreateCommand())
            {
                cmd.CommandText = "select * from invoice where DocNumber=" + paramPrefix + "DocNumber and InvoiceDate>=" + paramPrefix + "DocDate1 and InvoiceDate<=" + paramPrefix + "DocDate2 and StorageNameExternalCode=" + paramPrefix + "StorageCode" + (docDate != "" ? " and InvoiceDate=" + paramPrefix + "DocDate" : "");
                cmd.CommandType = CommandType.Text;

                var inval = cmd.CreateParameter();
                inval.ParameterName = "DocNumber";
                inval.DbType        = DbType.String;
                inval.Value         = docNumber;
                cmd.Parameters.Add(inval);

                inval = cmd.CreateParameter();
                inval.ParameterName = "DocDate1";
                inval.DbType        = DbType.Date;
                inval.Value         = DateTime.ParseExact("01.01." + docYear, "dd.MM.yyyy", culture);
                cmd.Parameters.Add(inval);

                inval = cmd.CreateParameter();
                inval.ParameterName = "DocDate2";
                inval.DbType        = DbType.Date;
                inval.Value         = DateTime.ParseExact("31.12." + docYear, "dd.MM.yyyy", culture);
                cmd.Parameters.Add(inval);

                inval = cmd.CreateParameter();
                inval.ParameterName = "StorageCode";
                inval.DbType        = DbType.String;
                inval.Value         = currentStorage.Externalcode;
                cmd.Parameters.Add(inval);

                if (docDate != "")
                {
                    inval = cmd.CreateParameter();
                    inval.ParameterName = "DocDate";
                    inval.DbType        = DbType.Date;
                    inval.Value         = DateTime.ParseExact(docDate, "dd.MM.yyyy", culture);
                    cmd.Parameters.Add(inval);
                }

                try
                {
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            rowCount++;
                            COMING_SAP item = new COMING_SAP();
                            item.DocNumber = Convert.ToString(reader["DOCNUMBER"]);
                            if (reader["INVOICEDATE"] != null)
                            {
                                item.DocDate = ((DateTime)reader["INVOICEDATE"]).ToString(DataGlobals.DATE_FORMAT_FULL_YEAR);
                            }
                            else
                            {
                                Message = "В накладной " + docNumber + " отсутствует дата!";
                            }
                            item.StorageNameExternalCode = Convert.ToString(reader["STORAGENAMEEXTERNALCODE"]);
                            item.StorageName             = Convert.ToString(reader["STORAGENAME"]);
                            item.ExternalCode            = Convert.ToString(reader["EXTERNALCODE"]);
                            item.QUANTITY = Convert.ToInt32(reader["QUANTITY"]);

                            item.DocTypeId = DocTypeId;
                            model.Add(item);
                        }
                        reader.Close();
                    }
                }
                catch (Exception e)
                {
                    Message = e.Message;
                }
            }

            if (model.GroupBy(g => g.DocNumber, g => g.DocDate).Count() > 1)
            {
                Message = "С номером " + model[0].DocNumber + " несколько документов!!! Укажите точную дату документа";
                model.Clear();
            }
            else
            {
                param.Clear();
                param.Add("Organization.Id", currentOrganization.Id);
                foreach (var item in model)
                {
                    param["ExternalCode"] = item.ExternalCode;
                    //param.Add("IsActive", true);
                    IList <Nomenclature> nomenclatures = nomenRepository.GetByLikeCriteria(param);
                    if (nomenclatures.Count != 0)
                    {
                        Nomenclature nomenclature = nomenclatures[0];
                        item.MaterialId = nomenclature.ExternalCode;
                        if (nomenclature.Growth != null)
                        {
                            item.GrowthId   = nomenclature.Growth.Id;
                            item.GrowthName = nomenclature.Growth.SizeNumber;
                        }
                        item.IsWinter        = nomenclature.NomGroup.IsWinter;
                        item.MATERIAL        = nomenclature.Name;
                        item.NomBodyPartId   = nomenclature.NomBodyPart.Id;
                        item.NomBodyPartName = nomenclature.NomBodyPart.Name;
                        item.NomGroupId      = nomenclature.NomGroup.Id;
                        item.NomGroupName    = nomenclature.NomGroup.Name;
                        item.SexId           = nomenclature.Sex.Id;
                        item.SexName         = nomenclature.Sex.Name;
                        if (nomenclature.NomBodyPartSize != null)
                        {
                            item.SizeId   = nomenclature.NomBodyPartSize.Id;
                            item.SizeName = nomenclature.NomBodyPartSize.SizeNumber;
                        }
                        item.UnitId   = nomenclature.Unit.Id;
                        item.UnitName = nomenclature.Unit.Name;
                    }
                    else
                    {
                        item.SexName = "";
                    }
                }
            }

            return(model);
        }
Beispiel #8
0
        public void SaveOnStorage(HttpResponseBase response, String date, int storageNameId, IEnumerable <HttpPostedFileBase> attachments)
        {
            // The Name of the Upload component is "attachments"
            IFormatProvider culture     = new System.Globalization.CultureInfo("ru-RU", true);
            StorageName     storageName = storageNameRepository.Get(storageNameId);

            if (storageName == null)
            {
                response.Write("Выбранный склад не найден в БД!<br/>");
                response.Flush();
                return;
            }
            DateTime remaindDate;

            DateTime.TryParseExact(date, DataGlobals.DATE_FORMAT_FULL_YEAR, null, System.Globalization.DateTimeStyles.None, out remaindDate);
            if (remaindDate == null)
            {
                response.Write("Ошибка в дате остатков!<br/>");
                response.Flush();
                return;
            }

            foreach (var file in attachments)
            {
                // Some browsers send file names with full path. This needs to be stripped.
                var isError  = false;
                var fileName = Path.GetFileName(file.FileName);
                response.Write("Обрабатывается файл <b>" + fileName + "</b><br/>");
                response.Flush();
                var physicalFilePath = Path.Combine(Server.MapPath("~/TempFiles"), fileName);
                try
                {
                    if (System.IO.File.Exists(physicalFilePath))
                    {
                        System.IO.File.Delete(physicalFilePath);
                    }
                    try
                    {
                        file.SaveAs(physicalFilePath);
                    }
                    catch (Exception e)
                    {
                        response.Write("Ошибка при охранении файла на сервере:<br/>");
                        response.Write(e.Message);
                        response.Flush();
                        isError = true;
                    }
                    System.Data.DataTable table = null;
                    string workSheetNames       = "";
                    if (!isError)
                    {
                        try
                        {
                            ExcelReader excelReader = new ExcelReader(physicalFilePath, true);
                            if (excelReader.workSheetNames.Length > 0)
                            {
                                workSheetNames = excelReader.workSheetNames[0];
                                table          = excelReader.GetWorksheet(workSheetNames);
                            }
                            else
                            {
                                response.Write("В файле не найден рабочий лист!<br/>");
                                response.Flush();
                                isError = true;
                            }
                        }
                        catch (Exception e)
                        {
                            response.Write("Ошибка при открытии файла:<br/>");
                            response.Write(e.Message);
                            response.Flush();
                            isError = true;
                        }
                    }
                    if (table != null)
                    {
                        response.Write("Загрузка данных производится из листа с именем '" + workSheetNames.Trim(new[] { '$' }) + "'<br/>");
                        response.Flush();
                        //if (!table.Columns.Contains("Код склада"))
                        //{
                        //    response.Write("Файл содержит не коррекные данные ('Код склада').<br/>");
                        //    isError = true;
                        //}
                        if (!table.Columns.Contains("Номенклатурный номер"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Номенклатурный номер').<br/>");
                            response.Flush();
                            isError = true;
                        }
                        if (!table.Columns.Contains("Износ"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Износ').<br/>");
                            response.Flush();
                            isError = true;
                        }
                        if (!table.Columns.Contains("Кол-во"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Кол-во').<br/>");
                            response.Flush();
                            isError = true;
                        }
//                            int colStorage = table.Columns.IndexOf("Код склада");
                        int colNomenclature = table.Columns.IndexOf("Номенклатурный номер");
                        int colWear         = table.Columns.IndexOf("Износ");
                        int colCount        = table.Columns.IndexOf("Кол-во");

                        if (!isError)
                        {
                            //                                    DataRow[] result = table.Select("F2 = '*' and F3=" + storageName.Plant + " and F4 in (" + storageName.StorageNumber + ")");

                            //remaindRepository.TruncRamains(storageNameId, date,null);

                            // Удаление ранее расчитаных остатков
                            //storageRepository.TruncStorage(storageNameId);

                            DataRow[] result = table.Select();
                            Dictionary <string, object> queryParams = new Dictionary <string, object>();
                            int          idOrg      = int.Parse(getCurrentEnterpriseId());
                            Organization currentOrg = organizationRepository.Get(idOrg);
                            foreach (DataRow row in result)     // Loop over the rows.
                            {
                                if (row[colNomenclature] != System.DBNull.Value)
                                {
                                    // Ищем id номенклатуры на руках( сверила все номенклатуры, в справочнике есть все)
                                    queryParams.Clear();
                                    queryParams.Add("Organization", currentOrg);
                                    queryParams.Add("ExternalCode", row[colNomenclature].ToString());
                                    queryParams.Add("IsActive", true);
                                    IList <Nomenclature> nomenclatures = nomenclatureRepository.GetByLikeCriteria(queryParams);
                                    if (nomenclatures.Count == 0)
                                    {
                                        queryParams.Clear();
                                        queryParams.Add("Organization", currentOrg);
                                        queryParams.Add("ExternalCode", row[colNomenclature].ToString());
                                        queryParams.Add("IsActive", false);
                                        nomenclatures = nomenclatureRepository.GetByLikeCriteria(queryParams);
                                        if (nomenclatures.Count == 0)
                                        {
                                            response.Write("Номенклатура с № " + row[colNomenclature].ToString() + " не найдена в системе!<br/>");
                                            response.Flush();
                                            continue;
                                        }
                                    }

                                    int quantity = 0;
                                    if (!int.TryParse(row[colCount].ToString(), out quantity))
                                    {
                                        response.Write("У номенклатуры " + row[colNomenclature] + " ошибка в кол-ве!<br/>");
                                        response.Flush();
                                        continue;
                                    }


                                    string wear = row[colWear].ToString();
                                    if ((wear != "100") && (wear != "50"))
                                    {
                                        response.Write("У номенклатуры " + row[colNomenclature] + " ошибка в износе! Допустимые изачения 100 или 50. <br/>");
                                        response.Flush();
                                        continue;
                                    }

                                    // Ищем есть ли подобная позиция на складе (номенклатура+рост+размер), считаем, что % годностиу всех 100
                                    // Если не находим, то добавляем запись на склад с нулевым кол-вом
                                    queryParams.Clear();
                                    queryParams.Add("StorageName", storageName);
                                    queryParams.Add("Nomenclature", nomenclatures[0]);
                                    queryParams.Add("Wear", wear);
                                    //Storage storage = storageRepository.FindOne(queryParams);
                                    IList <Storage> storages = storageRepository.GetByLikeCriteria(queryParams);
                                    Storage         storage  = null;
                                    if (storages.Count > 0)
                                    {
                                        storage = storages[0];
                                    }

                                    if (storage == null)
                                    {
                                        storage              = new Storage();
                                        storage.StorageName  = storageName;
                                        storage.Nomenclature = nomenclatures[0];
                                        storage.Quantity     = quantity;
                                        storage.Wear         = wear;
                                        storageRepository.SaveOrUpdate(storage);
                                    }
                                    else
                                    {
                                        storage.Quantity = storage.Quantity + quantity;
                                    }
                                    storage.NomBodyPartSize = nomenclatures[0].NomBodyPartSize;
                                    storage.Growth          = nomenclatures[0].Growth;

                                    Remaind remaind = new Remaind();
                                    remaind.Growth          = nomenclatures[0].Growth;
                                    remaind.Nomenclature    = nomenclatures[0];
                                    remaind.Quantity        = quantity;
                                    remaind.Wear            = int.Parse(wear);
                                    remaind.StorageName     = storageName;
                                    remaind.RemaindDate     = remaindDate;
                                    remaind.NomBodyPartSize = nomenclatures[0].NomBodyPartSize;
                                    remaind.ActualDate      = DateTime.Now;

                                    try
                                    {
                                        storageRepository.DbContext.BeginTransaction();
                                        storageRepository.SaveOrUpdate(storage);
                                        remaind.Storage = storage;
                                        remaindRepository.SaveOrUpdate(remaind);
                                        storageRepository.DbContext.CommitTransaction();
                                    }
                                    catch (Exception e)
                                    {
                                        isError = true;
                                        response.Write("Для номенклатуры " + row[colNomenclature] + " произошла ошибка при сохранении данных в БД:<br/>");
                                        response.Write(e.Message);
                                        response.Write("<br/>");
                                        if (e.InnerException != null)
                                        {
                                            response.Write(e.InnerException.Message);
                                            response.Write("<br/>");
                                        }
                                        response.Flush();
                                        storageRepository.DbContext.RollbackTransaction();
                                    }
                                }
                            }
                            response.Flush();
                        }
                        response.Flush();
                    }
                    if (!isError)
                    {
                        response.Write("Файл успешно обработан!");
                    }
                }
                finally
                {
                    System.IO.File.Delete(physicalFilePath);
                }
            }
        }
Beispiel #9
0
        public void SaveOnHand(HttpResponseBase response, string loadDate, int operTypeId, IEnumerable <HttpPostedFileBase> attachments)
        {
            // The Name of the Upload component is "attachments"
            IFormatProvider culture = new System.Globalization.CultureInfo("ru-RU", true);
            DateTime        operationDate;

            DateTime.TryParseExact(loadDate, DataGlobals.DATE_FORMAT_FULL_YEAR, null, System.Globalization.DateTimeStyles.None, out operationDate);
            if (operationDate == Null_Date)
            {
                response.Write("Ошибка в дате операции!<br/>");
                response.Flush();
                return;
            }
            foreach (var file in attachments)
            {
                // Some browsers send file names with full path. This needs to be stripped.
                var isError  = false;
                var fileName = Path.GetFileName(file.FileName);
                response.Write("Обрабатывается файл <b>" + fileName + "</b><br/>");
                response.Flush();
                var physicalFilePath = Path.Combine(Server.MapPath("~/TempFiles"), fileName);
                try
                {
                    if (System.IO.File.Exists(physicalFilePath))
                    {
                        System.IO.File.Delete(physicalFilePath);
                    }
                    try
                    {
                        file.SaveAs(physicalFilePath);
                    }
                    catch (Exception e)
                    {
                        response.Write("Ошибка при охранении файла на сервере:<br/>");
                        response.Write(e.Message);
                        response.Flush();
                        isError = true;
                    }
                    System.Data.DataTable table = null;
                    string workSheetNames       = "";
                    if (!isError)
                    {
                        try
                        {
                            ExcelReader excelReader = new ExcelReader(physicalFilePath, true);
                            if (excelReader.workSheetNames.Length > 0)
                            {
                                workSheetNames = excelReader.workSheetNames[0];
                                table          = excelReader.GetWorksheet(workSheetNames);
                            }
                            else
                            {
                                response.Write("В файле не найден рабочий лист!<br/>");
                                response.Flush();
                                isError = true;
                            }
                        }
                        catch (Exception e)
                        {
                            response.Write("Ошибка при открытии файла:<br/>");
                            response.Write(e.Message);
                            response.Flush();
                            isError = true;
                        }
                    }
                    if (table != null)
                    {
                        response.Write("Загрузка данных производится из листа с именем '" + workSheetNames.Trim(new[] { '$' }) + "'<br/>");
                        response.Flush();
                        if (!table.Columns.Contains("Табельный номер"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Табельный номер').<br/>");
                            response.Flush();
                            isError = true;
                        }
                        if (!table.Columns.Contains("Номенклатурный номер"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Номенклатурный номер').<br/>");
                            response.Flush();
                            isError = true;
                        }
                        if (!table.Columns.Contains("Дата выдачи"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Дата выдачи').<br/>");
                            response.Flush();
                            isError = true;
                        }
                        if (!table.Columns.Contains("Кол-во"))
                        {
                            response.Write("Файл содержит не коррекные данные ('Кол-во').<br/>");
                            response.Flush();
                            isError = true;
                        }

                        /*
                         * if (!table.Columns.Contains("Период"))
                         * {
                         *  response.Write("Файл содержит не коррекные данные ('Период').<br/>");
                         *  response.Flush();
                         *  isError = true;
                         * }
                         */
                        int colTabN         = table.Columns.IndexOf("Табельный номер");
                        int colNomenclature = table.Columns.IndexOf("Номенклатурный номер");
                        int colDate         = table.Columns.IndexOf("Дата выдачи");
                        int colCount        = table.Columns.IndexOf("Кол-во");
                        int colUsePeriod    = -1;
                        if (!table.Columns.Contains("Период"))
                        {
                            colUsePeriod = table.Columns.IndexOf("Период");
                        }

                        if (!isError)
                        {
                            //                                    DataRow[] result = table.Select("F2 = '*' and F3=" + storageName.Plant + " and F4 in (" + storageName.StorageNumber + ")");
                            DataRow[] result = table.Select();
                            Dictionary <string, object> queryParams = new Dictionary <string, object>();
                            Dictionary <string, object> orderParams = new Dictionary <string, object>();
                            int          idOrg      = int.Parse(getCurrentEnterpriseId());
                            Organization currentOrg = organizationRepository.Get(idOrg);
                            Motiv        motiv      = motivRepository.Get(DataGlobals.MOTIVID_TRANSFER);
                            foreach (DataRow row in result) // Loop over the rows.
                            {
                                if (row[colTabN] != System.DBNull.Value)
                                {
                                    int tabN     = int.Parse(row[colTabN].ToString());
                                    int quantity = 0;
                                    if (!int.TryParse(row[colCount].ToString(), out quantity))
                                    {
                                        response.Write("У человека с Таб.№ " + tabN + " ошибка в кол-ве!<br/>");
                                        response.Flush();
                                        continue;
                                    }

                                    DateTime startDate;
                                    String   rowDate = row[colDate].ToString();
                                    if (rowDate.IndexOf(' ') > 0)
                                    {
                                        rowDate = rowDate.Substring(0, rowDate.IndexOf(' '));
                                    }
                                    DateTime.TryParseExact(rowDate, DataGlobals.DATE_FORMAT_FULL_YEAR, null, System.Globalization.DateTimeStyles.None, out startDate);

                                    if (startDate == Null_Date)
                                    {
                                        response.Write("У человека с Таб.№ " + tabN + " ошибочная дата выдачи!<br/>");
                                        response.Flush();
                                        continue;
                                    }

                                    if (startDate > DateTime.Now)
                                    {
                                        response.Write("У человека с Таб.№ " + tabN + " дата выдачи больше текущей даты!<br/>");
                                        response.Flush();
                                        continue;
                                    }
                                    int useperiod = 0;
                                    if (colUsePeriod >= 0)
                                    {
                                        useperiod = int.Parse(row[colUsePeriod].ToString());
                                    }

                                    // Ищем id работника  по табельному номеру, если не находим, то не берем его
                                    queryParams.Clear();
                                    queryParams.Add("RootOrganization", currentOrg.Id);
                                    //queryParams.Add("IsActive", true);
                                    queryParams.Add("TabN", tabN);
                                    Worker correntWorker = workerRepository.FindOne(queryParams);
                                    if (correntWorker == null)
                                    {
                                        response.Write("Человека с Таб.№ " + tabN + " нет в базе!<br/>");
                                        response.Flush();
                                        continue;
                                    }
                                    // Ищем ID рабочего места
                                    queryParams.Clear();
                                    queryParams.Add("RootOrganization", currentOrg.Id);
                                    queryParams.Add("Worker", correntWorker);
                                    // Будем ипользовать последнее место работы
                                    orderParams.Clear();
                                    orderParams.Add("BeginDate", DESC);
                                    orderParams.Add("IsActive", DESC);

                                    IList <WorkerWorkplace> workerWorkplaces = workerWorkplaceRepository.GetByLikeCriteria(queryParams, orderParams);
                                    // Ищем id номенклатуры на руках( сверила все номенклатуры, в справочнике есть все)
                                    queryParams.Clear();
                                    queryParams.Add("Organization", currentOrg);
                                    queryParams.Add("ExternalCode", row[colNomenclature].ToString());
                                    queryParams.Add("IsActive", true);
                                    IList <Nomenclature> nomenclatures = nomenclatureRepository.GetByLikeCriteria(queryParams);
                                    if (nomenclatures.Count == 0)
                                    {
                                        queryParams.Clear();
                                        queryParams.Add("Organization", currentOrg);
                                        queryParams.Add("ExternalCode", row[colNomenclature].ToString());
                                        queryParams.Add("IsActive", false);
                                        nomenclatures = nomenclatureRepository.GetByLikeCriteria(queryParams);
                                        if (nomenclatures.Count == 0)
                                        {
                                            response.Write("Номенклатура с № " + row[colNomenclature].ToString() + " не найдена в системе!<br/>");
                                            response.Flush();
                                            continue;
                                        }
                                    }

                                    // Ищем склад
                                    queryParams.Clear();
                                    queryParams.Add("AreaCode", workerWorkplaces[0].Organization.AreaCode);
                                    queryParams.Add("Organization", currentOrg);

                                    //StorageName storageName = storageNameRepository.FindOne(queryParams);
                                    StorageName storageName = workerWorkplaces[0].Organization.StorageName;
                                    if (storageName == null)
                                    {
                                        response.Write("Для человека с Таб.№ " + tabN + "не найден склад!<br/>");
                                        response.Flush();
                                        continue;
                                    }

                                    operationRepository.DbContext.BeginTransaction();
                                    try
                                    {
                                        // Ищем есть ли подобная позиция на складе (номенклатура+рост+размер), считаем, что % годностиу всех 100
                                        // Если не находим, то добавляем запись на склад с нулевым кол-вом
                                        queryParams.Clear();
                                        queryParams.Add("StorageName", storageName);
                                        queryParams.Add("Nomenclature", nomenclatures[0]);
                                        queryParams.Add("Wear", "100");
                                        Storage storage = storageRepository.FindOne(queryParams);
                                        if (storage == null)
                                        {
                                            storage              = new Storage();
                                            storage.StorageName  = storageName;
                                            storage.Nomenclature = nomenclatures[0];
                                            storage.Quantity     = 0;
                                            storage.Wear         = "100";
                                            storageRepository.SaveOrUpdate(storage);
                                            storage.NomBodyPartSize = nomenclatures[0].NomBodyPartSize;
                                            storage.Growth          = nomenclatures[0].Growth;
                                        }
                                        OperType operType = operTypeRepository.Get(operTypeId);

                                        //OperType operType = operTypeRepository.Get(DataGlobals.OPERATION_WORKER_IN);
                                        //OperType operType = operTypeRepository.Get(DataGlobals.OPERATION_STORAGE_TRANSFER_IN);
                                        // Добавляем операцию постановки на забаланс , вместо последней выдачи
                                        queryParams.Clear();
                                        queryParams.Add("OperType", operType);
                                        queryParams.Add("DocNumber", "0");
                                        queryParams.Add("Storage", storage);
                                        queryParams.Add("WorkerWorkplace", workerWorkplaces[0]);
                                        Operation operation = operationRepository.FindOne(queryParams);
                                        if (operation == null)
                                        {
                                            operation           = new Operation();
                                            operation.DocNumber = "0";
                                            if (operType.Id == DataGlobals.OPERATION_STORAGE_TRANSFER_IN)
                                            {
                                                operation.DocDate  = operationDate;
                                                operation.OperDate = operationDate;
                                                operation.Motiv    = motiv;
                                            }
                                            else
                                            {
                                                operation.DocDate  = startDate;
                                                operation.OperDate = startDate;
                                            }
                                            operation.OperType        = operType;
                                            operation.Organization    = storageName.Organization;
                                            operation.Quantity        = quantity;
                                            operation.Wear            = "100";
                                            operation.StorageName     = storageName;
                                            operation.Storage         = storage;
                                            operation.WorkerWorkplace = workerWorkplaces[0];
                                            if (operation.OperType.Id == DataGlobals.OPERATION_WORKER_IN)
                                            {
                                                operation.GiveOperation = operation;
                                            }
                                            operationRepository.SaveOrUpdate(operation);
                                        }
                                        // Формируем личную карточку
                                        // Если нет шапки формируеруем шапку

                                        queryParams.Clear();
                                        queryParams.Add("WorkerWorkplace", workerWorkplaces[0]);
                                        WorkerCardHead workerCardHead = workerCardHeadRepository.FindOne(queryParams);
                                        if (workerCardHead == null)
                                        {
                                            workerCardHead = new WorkerCardHead();
                                            workerCardHead.WorkerWorkplace = workerWorkplaces[0];
                                            workerCardHeadRepository.SaveOrUpdate(workerCardHead);
                                        }
                                        // Формируем содержание личной карточки
                                        queryParams.Clear();
                                        queryParams.Add("Operation", operation);
                                        queryParams.Add("WorkerCardHead", workerCardHead);
                                        WorkerCardContent workerCardContent = workerCardContentRepository.FindOne(queryParams);
                                        if (workerCardContent == null)
                                        {
                                            workerCardContent                = new WorkerCardContent();
                                            workerCardContent.Operation      = operation;
                                            workerCardContent.Quantity       = quantity;
                                            workerCardContent.Storage        = storage;
                                            workerCardContent.WorkerCardHead = workerCardHead;
                                            workerCardContent.StartDate      = startDate;
                                            workerCardContent.UsePeriod      = useperiod;
                                            workerCardContentRepository.SaveOrUpdate(workerCardContent);
                                        }
                                        operationRepository.DbContext.CommitTransaction();
                                    }
                                    catch (Exception e)
                                    {
                                        operationRepository.DbContext.RollbackTransaction();
                                        response.Write("Ошибка при сохранении данных в БД:<br/>");
                                        response.Write(e.Message);
                                        response.Write("<br/>");
                                        if (e.InnerException != null)
                                        {
                                            response.Write(e.InnerException.Message);
                                            response.Write("<br/>");
                                        }
                                        isError = true;
                                        response.Flush();
                                    }
                                }
                            }
                            response.Flush();
                        }
                        response.Flush();
                    }
                    if (!isError)
                    {
                        response.Write("Файл успешно обработан!");
                    }
                }
                finally
                {
                    System.IO.File.Delete(physicalFilePath);
                }
            }
        }
Beispiel #10
0
 public static StorageName rebuildStorageName(StorageName inStorageName)
 {
     return(rebuildStorageName(inStorageName, null));
 }
Beispiel #11
0
 public override int GetHashCode()
 {
     return(StorageName.GetHashCode());
 }
 public bool Contains(StorageName storageName, ProfileId profileId, TypeNameWithoutVersion key, object item)
 {
     return(FindBy(storageName, profileId, key, item) != null);
 }
 public ProfileStorage FindBy(StorageName storageName, ProfileId profileId, TypeNameWithoutVersion key, object item)
 {
     return(FindBy(profileId, key).Where(x => x.GetValue() == item && storageName.Value == x.Name).FirstOrDefault());
 }
        public ActionResult _TransferWorkerCard(int?workerWorkplaceId, int storageNameId, string listId, Boolean outNorma, string OperDate)
        {
            DateTime operDate;

            DateTime.TryParseExact(OperDate, DataGlobals.DATE_FORMAT, null, System.Globalization.DateTimeStyles.None, out operDate);
            ResultState resultState = new ResultState();

            resultState.Status = ResultState.OK;
            if (workerWorkplaceId != null)
            {
                Dictionary <string, object> query = new Dictionary <string, object>();
                Dictionary <string, object> order = new Dictionary <string, object>();
                query.Add("Worker.Id", workerWorkplaceId);
                query.Add("IsActive", true);
                order.Add("Storage.StorageName.Id", storageNameId);
                //Выбираем активные рабочие места
                IList <WorkerWorkplace> workerWorkplaces = workerWorkplaceRepository.GetByLikeCriteria(query);
                if (workerWorkplaces.Count == 1)
                {
                    WorkerWorkplace ww = workerWorkplaces[0];
                    //Выбираем активные рабочие места
                    // Запрет на одевание работника в салоне к которому он не приписан. Пока закомментировала, т.к. не уверена, что не будет последствий

                    /*
                     * if (ww.Organization.StorageName.Id != storageNameId)
                     * {
                     *  resultState.Status = ResultState.ERROR;
                     *  resultState.setMessage("НЕЛЬЗЯ ВЫПОЛНИТЬ ПЕРЕВОД!!! Работник приписан к складу " + ww.Organization.StorageName.StorageNumber);
                     * }
                     */
                    string   periodDateStr  = getConfigParamValue(configRepository, "periodDate", getCurrentEnterpriseId());
                    string   periodIsClosed = getConfigParamValue(configRepository, "periodIsClosed", getCurrentEnterpriseId());
                    DateTime periodDate;
                    DateTime.TryParseExact(periodDateStr, DataGlobals.DATE_FORMAT_FULL_YEAR, null, System.Globalization.DateTimeStyles.None, out periodDate);

                    // проверка на закрытие периода
                    if (periodIsClosed != null && periodIsClosed.Equals("1") && periodDate > operDate)
                    {
                        resultState.Status = ResultState.ERROR;
                        resultState.setMessage(OperDate + ": Период закрыт для изменений");
                    }

                    if (resultState.Status == ResultState.OK)
                    {
                        query.Clear();
                        query.Add("WorkerWorkplace", ww);
                        WorkerCardHead newWorkerCardHead = workerCardRepository.FindOne(query);
                        if (newWorkerCardHead == null)
                        {
                            newWorkerCardHead = new WorkerCardHead();
                            newWorkerCardHead.WorkerWorkplace = ww;
                        }
                        query.Clear();
                        query.Add("Organization", ww.Organization);
                        query.Add("Norma.Organization.Id", int.Parse(getCurrentEnterpriseId()));
                        query.Add("Norma.IsActive", true);
                        IList <NormaOrganization>  normaOrganizations = normaOrganizationRepository.GetByCriteria(query);
                        IList <NomenclatureSimple> list = getNomenclaturesByParam(listId);
                        string docNumber = "00000";
                        // Убрала ниже, чтобы можно было изменять номер документа
                        docNumber = operationRepository.GetNextDocNumber(DataGlobals.OPERATION_STORAGE_TRANSFER_OUT, getCurrentEnterpriseId());
                        int?skladId = null;
                        foreach (var item in list)
                        {
                            ResultState listResultState = new ResultState();
                            listResultState.Status = ResultState.OK;

                            WorkerCardContent oldWorkerCardContent = workerCardContentRepository.Get(item.Id);
                            if (skladId != null && skladId != oldWorkerCardContent.Storage.StorageName.Id)
                            {
                                docNumber = operationRepository.GetNextDocNumber(DataGlobals.OPERATION_STORAGE_TRANSFER_OUT, getCurrentEnterpriseId());
                            }

                            if (oldWorkerCardContent.StartDate >= operDate)
                            {
                                listResultState.Status = ResultState.ERROR;
                                listResultState.setMessage(item.Name + "   Дата перевода раньше даты выдачи!!! Введите текущую дату!");

                                resultState.Status = ResultState.ERROR;
                                resultState.setMessage(item.Name + "   Дата перевода раньше даты выдачи!!! Введите текущую дату!");
                            }

                            NormaContent newNormaContent = GetNewNormaContent(normaOrganizations, item.GroupId);
                            // Если на новом рабочем месте номенклатура не подходит по норме и выбрана опция
                            //Ставим старую норму
                            //Закомментировано, т.к. по просьбе УПУ не нужно переносить на руки, то что не по норме
                            if (newNormaContent == null && outNorma == true)
                            {
                                newNormaContent = oldWorkerCardContent.NormaContent;
                            }
//                        if (newNormaContent != null )
                            if (newNormaContent == null && outNorma != true)
                            {
                                listResultState.Status = ResultState.ERROR;
                                listResultState.setMessage(item.Name + " НЕ СООТВЕТСТВУЕТ новой норме. Выполните ВОЗВРАТ или СПИСАНИЕ по акту!");

                                resultState.Status = ResultState.ERROR;
                                resultState.setMessage(item.Name + " НЕ СООТВЕТСТВУЕТ новой норме. Выполните ВОЗВРАТ или СПИСАНИЕ по акту!");
                            }
                            else
                            {
                                Storage storageTo = null;
                                //Выбранный склад и склад номенклатуры совпадают
                                if (oldWorkerCardContent.Storage.StorageName.Id == storageNameId)
                                {
                                    storageTo = oldWorkerCardContent.Storage;
                                }
                                //Выбранный склад и склад номенклатуры не совпадают
                                else
                                {
                                    //Пытаемся найти номенклатуру на другом складе
                                    StorageName storageName = storageNameRepository.Get(storageNameId);
                                    if (storageName == null)
                                    {
                                        listResultState.Status = ResultState.ERROR;
                                        listResultState.setMessage("В справочнике не найден склад с идентификатором " + storageNameId + "!");

                                        resultState.Status = ResultState.ERROR;
                                        resultState.setMessage("В справочнике не найден склад с идентификатором " + storageNameId + "!");
                                    }
                                    if (listResultState.Status == ResultState.OK)
                                    {
                                        query.Clear();
                                        query.Add("Nomenclature", oldWorkerCardContent.Storage.Nomenclature);
                                        query.Add("StorageName", storageName);
                                        if (oldWorkerCardContent.Storage.Wear == null)
                                        {
                                            query.Add("[]Wear", "");
                                        }
                                        else
                                        {
                                            query.Add("Wear", oldWorkerCardContent.Storage.Wear);
                                        }
                                        if (oldWorkerCardContent.Storage.Growth == null)
                                        {
                                            query.Add("[]Growth", "");
                                        }
                                        else
                                        {
                                            query.Add("Growth", oldWorkerCardContent.Storage.Growth);
                                        }
                                        if (oldWorkerCardContent.Storage.NomBodyPartSize == null)
                                        {
                                            query.Add("[]NomBodyPartSize", "");
                                        }
                                        else
                                        {
                                            query.Add("NomBodyPartSize", oldWorkerCardContent.Storage.NomBodyPartSize);
                                        }
                                        IList <Storage> storages = storageRepository.GetByLikeCriteria(query);
                                        if (storages.Count > 0)
                                        {
                                            storageTo = storages[0];
                                        }
                                        else
                                        {
                                            //На новом складе не нашлась номенклатура
                                            storageTo                 = new Storage();
                                            storageTo.StorageName     = storageName;
                                            storageTo.Nomenclature    = oldWorkerCardContent.Storage.Nomenclature;
                                            storageTo.Quantity        = 0;
                                            storageTo.Price           = oldWorkerCardContent.Storage.Price;
                                            storageTo.Growth          = oldWorkerCardContent.Storage.Growth;
                                            storageTo.NomBodyPartSize = oldWorkerCardContent.Storage.NomBodyPartSize;
                                            storageTo.Wear            = oldWorkerCardContent.Storage.Wear;
                                            storageRepository.SaveOrUpdate(storageTo);
                                        }
                                    }
                                }
//                            if (resultState.Status == ResultState.OK)
                                if (listResultState.Status == ResultState.OK)

                                {
                                    //Создаем операцию на перевод по старому месту работы
                                    Operation oldOperation = new Operation();
                                    oldOperation.WorkerWorkplace = oldWorkerCardContent.WorkerCardHead.WorkerWorkplace;
                                    oldOperation.OperDate        = operDate; //DateTime.Now;
                                    oldOperation.Quantity        = oldWorkerCardContent.Quantity;
                                    oldOperation.OperType        = operTypeRepository.Get(DataGlobals.OPERATION_STORAGE_TRANSFER_OUT);
                                    oldOperation.Organization    = organizationRepository.Get(int.Parse(getCurrentEnterpriseId()));
                                    oldOperation.DocNumber       = docNumber;
                                    oldOperation.GiveOperation   = oldWorkerCardContent.GiveOperation;
                                    //oldOperation.DocDate=
                                    query.Clear();
                                    query.Add("OperType", oldOperation.OperType);
                                    IList <Motiv> motivs = motivRepository.GetByLikeCriteria(query);
                                    if (motivs.Count > 0)
                                    {
                                        oldOperation.Motiv = motivs[0];
                                    }
                                    oldOperation.Storage = oldWorkerCardContent.Storage;

                                    //Создаем операцию на перевод по новому месту работы
                                    Operation newOperation = new Operation();
                                    newOperation.WorkerWorkplace = ww;
                                    newOperation.OperDate        = operDate; //DateTime.Now;
                                    newOperation.Quantity        = oldWorkerCardContent.Quantity;
                                    newOperation.OperType        = operTypeRepository.Get(DataGlobals.OPERATION_STORAGE_TRANSFER_IN);
                                    newOperation.Organization    = organizationRepository.Get(int.Parse(getCurrentEnterpriseId()));
                                    newOperation.DocNumber       = docNumber;
                                    newOperation.GiveOperation   = oldWorkerCardContent.GiveOperation;
                                    //newOperation.DocDate=

                                    motivs.Clear();
                                    query.Clear();
                                    query.Add("OperType", newOperation.OperType);
                                    motivs = motivRepository.GetByLikeCriteria(query);
                                    if (motivs.Count > 0)
                                    {
                                        newOperation.Motiv = motivs[0];
                                    }
                                    newOperation.Storage = storageTo;

                                    newOperation.TransferOperation = oldOperation;
                                    oldOperation.TransferOperation = newOperation;

                                    operationRepository.SaveOrUpdate(oldOperation);
                                    operationRepository.SaveOrUpdate(newOperation);
                                    //Создаем новую карточку
                                    WorkerCardContent newWorkerCardContent = new WorkerCardContent();
                                    newWorkerCardContent.WorkerCardHead = newWorkerCardHead;
                                    newWorkerCardContent.Storage        = storageTo;
                                    newWorkerCardContent.Quantity       = oldWorkerCardContent.Quantity;
                                    newWorkerCardContent.Operation      = newOperation;
                                    newWorkerCardContent.StartDate      = oldWorkerCardContent.StartDate;
                                    newWorkerCardContent.UsePeriod      = oldWorkerCardContent.UsePeriod;
                                    newWorkerCardContent.GiveOperation  = oldWorkerCardContent.GiveOperation;

                                    //Проставляем новую норму!!!
                                    newWorkerCardContent.NormaContent = newNormaContent;
                                    //Обнуляем старую карточку
                                    oldWorkerCardContent.Quantity   = 0;
                                    oldWorkerCardContent.EndDate    = operDate; //DateTime.Now;
                                    oldWorkerCardContent.OperReturn = oldOperation;
                                    //Сохраняем новую и старую карточки
                                    workerCardContentRepository.SaveOrUpdate(oldWorkerCardContent);
                                    workerCardContentRepository.SaveOrUpdate(newWorkerCardContent);
                                }
                            }

                            skladId = oldWorkerCardContent.Storage.StorageName.Id;
                        }
                    }
                }
                else
                {
                    //У человека несколько активных рабочих мест или рабочее место не найдено
                    resultState.Status = ResultState.ERROR;
                    resultState.setMessage("У человека больше одного рабочего места или рабочее место не найдено!");
                }
            }
            return(Json(resultState));
        }
Beispiel #15
0
        public List <COMING_SAP> GetInvoice(Organization currentOrganization, StorageName currentStorage, ICriteriaRepository <Nomenclature> nomenRepository, ICriteriaRepository <NomGroup> nomGroupRepository, int DocTypeId, string docNumber, int docYear, string docDate, out string Message)
        {
            String            INCOMING_RFC = ConfigurationManager.AppSettings["SAP_ERP_" + currentOrganization.Id];
            RfcDestination    destination  = RfcDestinationManager.GetDestination(INCOMING_RFC);
            IRfcFunction      function     = null;
            List <COMING_SAP> list         = new List <COMING_SAP>();

//            string docDate = "01.01." + docYear;
            docDate = "01.01." + docYear;

            if (currentStorage == null)
            {
                currentStorage = new StorageName();
            }
            try
            {
                function = destination.Repository.CreateFunction("BAPI_GOODSMVT_GETDETAIL");

                function.SetValue("MATERIALDOCUMENT", docNumber);
                function.SetValue("MATDOCUMENTYEAR", docYear);
                function.Invoke(destination);
            }
            catch (RfcBaseException e)
            {
                Message = e.StackTrace;
                //                Console.WriteLine(e.ToString());
            }
            Dictionary <string, Nomenclature> MaterialName          = new Dictionary <string, Nomenclature>();
            Dictionary <string, string>       NomenclatureGroupName = new Dictionary <string, string>();

            Message = "OK";
            IRfcStructure tableHeader = function.GetStructure("GOODSMVT_HEADER");

            if (tableHeader.Count > 0)
            {
                if (tableHeader.GetString("DOC_DATE") != "0000-00-00")
                {
                    docDate = tableHeader.GetString("DOC_DATE");
                    try
                    {
                        docDate = DateTime.ParseExact(docDate, "yyyy-MM-dd", new System.Globalization.CultureInfo("ru-RU", true)).ToString(DataGlobals.DATE_FORMAT_FULL_YEAR);
                    }
                    catch
                    {
                    }
                }
            }
            IRfcTable table = function.GetTable("GOODSMVT_ITEMS");

            if (table.RowCount == 0)
            {
                IRfcTable retTable = function.GetTable("RETURN");
                retTable.CurrentIndex = 0;
                Message = retTable.GetString("MESSAGE");
            }
            else
            {
                for (int i = 0; i < table.RowCount; i++)
                {
                    table.CurrentIndex = i;
                    if ((table.GetString("PLANT") == "" + currentStorage.Plant) && (table.GetString("STGE_LOC") == "" + currentStorage.Externalcode))
                    {
                        //if (getKnownMove(table.GetString("MOVE_TYPE"), currentStorage) != MoveType.Unknown)
                        //{
                        COMING_SAP incomingSap = new COMING_SAP(i + 1);
                        incomingSap.DocTypeId = DocTypeId;
                        incomingSap.DocNumber = docNumber;
                        //incomingSap.DocDate = "01.01." + docYear;
                        incomingSap.DocDate    = docDate;
                        incomingSap.MaterialId = table.GetString("MATERIAL").TrimStart('0');
                        Nomenclature defValue = null;
                        if (MaterialName.TryGetValue(incomingSap.MaterialId, out defValue))
                        {
                            incomingSap.MATERIAL     = defValue.Name;
                            incomingSap.ExternalCode = defValue.ExternalCode;
                            if (defValue.Growth != null)
                            {
                                incomingSap.GrowthId   = defValue.Growth.Id;
                                incomingSap.GrowthName = defValue.Growth.SizeNumber;
                            }
                            if (defValue.NomBodyPartSize != null)
                            {
                                incomingSap.SizeId   = defValue.NomBodyPartSize.Id;
                                incomingSap.SizeName = defValue.NomBodyPartSize.SizeNumber;
                            }
                            if (defValue.NomGroup != null)
                            {
                                incomingSap.NomGroupId   = defValue.NomGroup.Id;
                                incomingSap.NomGroupName = defValue.NomGroup.Name;
                                incomingSap.IsWinter     = defValue.NomGroup.IsWinter;
                            }
                            if (defValue.Sex != null)
                            {
                                incomingSap.SexId   = defValue.Sex.Id;
                                incomingSap.SexName = defValue.Sex.Name;
                            }
                            if (defValue.Unit != null)
                            {
                                incomingSap.UnitId   = defValue.Unit.Id;
                                incomingSap.UnitName = defValue.Unit.Name;
                            }
                            if (defValue.NomBodyPart != null)
                            {
                                incomingSap.NomBodyPartId   = defValue.NomBodyPart.Id;
                                incomingSap.NomBodyPartName = defValue.NomBodyPart.Name;
                            }
                        }
                        else
                        {
                            Dictionary <string, object> queryParams = new Dictionary <string, object>();
                            queryParams.Add("Organization", currentOrganization);
                            queryParams.Add("ExternalCode", incomingSap.MaterialId.TrimStart('0'));
                            queryParams.Add("IsActive", true);
                            //                                Nomenclature currentNomenclature = nomenRepository.FindOne(queryParams);
                            IList <Nomenclature> currentNomenclatures = nomenRepository.GetByLikeCriteria(queryParams);
                            Nomenclature         currentNomenclature  = null;
                            if (currentNomenclatures.Count > 0)
                            {
                                currentNomenclature = currentNomenclatures[0];
                            }
                            if (currentNomenclature != null)
                            {
                                // TODO: Требуется обновить группу номенклатуры из SAP?
                                defValue                 = currentNomenclature;
                                incomingSap.MATERIAL     = defValue.Name;
                                incomingSap.ExternalCode = defValue.ExternalCode;
                                if (defValue.NomGroup != null)
                                {
                                    incomingSap.NomGroupId   = defValue.NomGroup.Id;
                                    incomingSap.NomGroupName = defValue.NomGroup.Name;
                                    incomingSap.IsWinter     = defValue.NomGroup.IsWinter;
                                }
                                if (defValue.Sex != null)
                                {
                                    incomingSap.SexId   = defValue.Sex.Id;
                                    incomingSap.SexName = defValue.Sex.Name;
                                }
                                if (defValue.Unit != null)
                                {
                                    incomingSap.UnitId   = defValue.Unit.Id;
                                    incomingSap.UnitName = defValue.Unit.Name;
                                }
                                if (defValue.NomBodyPart != null)
                                {
                                    incomingSap.NomBodyPartId   = defValue.NomBodyPart.Id;
                                    incomingSap.NomBodyPartName = defValue.NomBodyPart.Name;
                                }
                            }
                            else
                            {
                                //Группу из сапа пока не запрашиваю!!!!

                                /*                                defValue = getMaterialName(destination, incomingSap.MaterialId);
                                 *                              if (NomenclatureGroupName.TryGetValue(incomingSap.NomrnclatureGroupId, out defStringValue))
                                 *                              {
                                 *                                  incomingSap.NomrnclatureGroupName = defStringValue;
                                 *                              }
                                 *                              else
                                 *                              {
                                 *                                  defStringValue = getNomenclatureGroupName(destination, incomingSap.NomrnclatureGroupId);
                                 *                                  incomingSap.NomrnclatureGroupName = defStringValue;
                                 *                                  NomenclatureGroupName.Add(incomingSap.NomrnclatureGroupId, defStringValue);
                                 *                              }*/
                                if (Message == "OK")
                                {
                                    Message = "";
                                }
                                defValue = new Nomenclature(int.Parse(incomingSap.MaterialId));
                                String[] strArray = getMaterialName(destination, table.GetString("MATERIAL"));
                                defValue.Name         = strArray[0];
                                defValue.ExternalCode = strArray[1].TrimStart('0');
                                Message = Message + "Номенклатура: [" + incomingSap.MaterialId + "]" + defValue.Name + "не найдена.\n";
                                incomingSap.MATERIAL     = defValue.Name;
                                incomingSap.ExternalCode = incomingSap.MaterialId;
                                queryParams.Clear();
                                queryParams.Add("Organization", currentOrganization);
                                queryParams.Add("ExternalCode", strArray[1].TrimStart('0'));
                                NomGroup nGroup = nomGroupRepository.FindOne(queryParams);
                                if (nGroup != null)
                                {
                                    incomingSap.NomGroupId      = nGroup.Id;
                                    incomingSap.NomGroupName    = nGroup.Name;
                                    incomingSap.IsWinter        = nGroup.IsWinter;
                                    incomingSap.NomBodyPartId   = nGroup.NomBodyPart.Id;
                                    incomingSap.NomBodyPartName = nGroup.NomBodyPart.Name;
                                }
                                incomingSap.SAPNomGroupId   = strArray[1].TrimStart('0');
                                incomingSap.SAPNomGroupName = getNomenclatureGroupName(destination, strArray[1]);
                                defValue.NomGroup           = nGroup;
                            }
                            if (defValue != null)
                            {
                                MaterialName.Add(incomingSap.MaterialId, defValue);
                            }
                        }

                        incomingSap.QUANTITY = (int)Math.Truncate(table.GetDouble("ENTRY_QNT"));
                        incomingSap.UOM      = table.GetString("ENTRY_UOM");
                        incomingSap.LC       = table.GetString("AMOUNT_LC");
                        incomingSap.SV       = table.GetString("AMOUNT_SV");
                        incomingSap.MoveType = table.GetString("MOVE_TYPE");
                        //NomenclatureInfo nInfo = getMaterialDetail(destination, incomingSap.MaterialId);
                        list.Add(incomingSap);
                        //}
                        //else {
                        //    Message = table.GetString("MOVE_TYPE") + " вид движения не поддерживается!";
                        //}
                    }
                }
            }
            return(list);
        }
Beispiel #16
0
        public ActionResult Save(string date, int StorageList, IEnumerable <HttpPostedFileBase> attachments)
        {
            int messCount = 0;

            if (attachments == null)
            {
                Session.Add("messRow" + messCount.ToString(), "Файл для загрузки не выбран");
                messCount++;
            }
            else
            {
                remaindExternalRepository.DbContext.BeginTransaction();
                // The Name of the Upload component is "attachments"
                IFormatProvider culture     = new System.Globalization.CultureInfo("ru-RU", true);
                string          format      = "dd.MM.yyyy";
                DateTime        paramDate   = DateTime.ParseExact(date, format, culture);
                StorageName     storageName = storageNameRepository.Get(StorageList);
                remaindExternalRepository.TruncRemainExternal(StorageList, date);
                foreach (var file in attachments)
                {
                    // Some browsers send file names with full path. This needs to be stripped.
                    var isError  = false;
                    var fileName = Path.GetFileName(file.FileName);
                    Session.Add("messRow" + messCount.ToString(), "Обрабатывается файл " + fileName);
                    messCount++;
                    var physicalFilePath = Path.Combine(Server.MapPath("~/TempFiles"), fileName);
                    try
                    {
                        if (System.IO.File.Exists(physicalFilePath))
                        {
                            System.IO.File.Delete(physicalFilePath);
                        }
                        try
                        {
                            file.SaveAs(physicalFilePath);
                        }
                        catch (Exception e)
                        {
                            Session.Add("messRow" + messCount.ToString(), "Ошибка при охранении файла на сервере:");
                            messCount++;
                            Session.Add("messRow" + messCount.ToString(), e.Message);
                            messCount++;
                            isError = true;
                        }
                        System.Data.DataTable table = null;
                        if (!isError)
                        {
                            try
                            {
                                ExcelReader excelReader = new ExcelReader(physicalFilePath);
                                table = excelReader.GetWorksheet(excelReader.workSheetNames[0]);
                            }
                            catch (Exception e)
                            {
                                Session.Add("messRow" + messCount.ToString(), "Ошибка при открытии файла:");
                                messCount++;
                                Session.Add("messRow" + messCount.ToString(), e.Message);
                                messCount++;
                                isError = true;
                            }
                        }
                        if (table != null)
                        {
                            try
                            {
                                DataRow[] result = table.Select("F2 = '*' and F3=" + storageName.Plant + " and F4 in (" + storageName.StorageNumber + ")");
                                Dictionary <string, object> queryParams = new Dictionary <string, object>();
                                foreach (DataRow row in result) // Loop over the rows.
                                {
                                    if (row[4] != System.DBNull.Value)
                                    {
                                        queryParams.Clear();
                                        queryParams.Add("Organization", storageName.Organization);
                                        queryParams.Add("ExternalCode", (string)row[4]);
                                        Nomenclature    nomenclature = nomenclatureRepository.FindOne(queryParams);
                                        RemaindExternal remExt       = new RemaindExternal();
                                        remExt.ActualDate   = DateTime.Now;
                                        remExt.RemaindDate  = paramDate;
                                        remExt.StorageName  = storageName;
                                        remExt.Nomenclature = nomenclature;
                                        remExt.Wear         = 100;
                                        String wear = (string)row[4];
                                        if ((wear.ToUpper(System.Globalization.CultureInfo.CurrentCulture) == "БУ") ||
                                            (wear.ToUpper(System.Globalization.CultureInfo.CurrentCulture) == "Б/У"))
                                        {
                                            remExt.Wear = 50;
                                        }
                                        remExt.ExternalCode = (string)row[4];
                                        int cnt = 0;
                                        if (row[11] != System.DBNull.Value)
                                        {
                                            int.TryParse((string)row[11], out cnt);
                                        }
                                        remExt.QuantityIn = cnt;
                                        cnt = 0;
                                        if (row[12] != System.DBNull.Value)
                                        {
                                            int.TryParse((string)row[12], out cnt);
                                        }
                                        remExt.QuantityOut = cnt;
                                        cnt = 0;
                                        if (row[13] != System.DBNull.Value)
                                        {
                                            int.TryParse((string)row[13], out cnt);
                                        }
                                        remExt.Quantity = cnt;
                                        remaindExternalRepository.SaveOrUpdate(remExt);
                                    }
                                }
                                Session.Add("messRow" + messCount.ToString(), "Обработано " + result.Length + " записей.");
                                messCount++;
                            }
                            catch (Exception e)
                            {
                                Session.Add("messRow" + messCount.ToString(), "Ошибка сохранении данных в БД:");
                                messCount++;
                                Session.Add("messRow" + messCount.ToString(), e.Message);
                                messCount++;
                                isError = true;
                            }
                        }
                        if (!isError)
                        {
                            remaindExternalRepository.DbContext.CommitTransaction();
                            Session.Add("messRow" + messCount.ToString(), "Файл успешно обработан");
                            messCount++;
                        }
                        else
                        {
                            remaindExternalRepository.DbContext.RollbackTransaction();
                        }
                    }
                    finally
                    {
                        System.IO.File.Delete(physicalFilePath);
                    }
                }
            }
            Session.Add("row_count", messCount.ToString());
            return(RedirectToAction("Index"));
        }