Exemplo n.º 1
0
        /// <summary>
        /// 上传适配器文件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult UploadAdapterAssembly(AdapterViewModel model)
        {
            return(ExecuteFunctionRun(() =>
            {
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
                ActionResult result = new ActionResult(true, "msgGlobalString.ImportSucced");

                if (files.Count > 0)
                {
                    string fileName = files[0].FileName;
                    if (Path.GetExtension(fileName).ToLower() != ".dll")
                    {
                        result.Success = false;
                        result.Message = "Adapter.Msg0";
                        return Json(result);
                    }

                    this.Engine.BizBus.RegisterAssembly(
                        files[0].FileName,
                        GetBytesFromStream(files[0].InputStream),
                        true);
                }

                return Json(result, JsonRequestBehavior.AllowGet);
            }));
        }
Exemplo n.º 2
0
        public static System.Collections.Generic.Dictionary <string, object> Upload(System.Web.HttpFileCollectionBase HttpFileCollectionBase, string DataSource, bool Rename, string[] Extension, int MaxFileCount)
        {
            var UploadError      = new System.Collections.Generic.List <string>();
            var UploadFile       = new System.Collections.Generic.List <string>();
            var UploadFileSource = new System.Collections.Generic.List <string>();
            var rs = new System.Collections.Generic.Dictionary <string, object>();

            if (HttpFileCollectionBase.Count < 1 || (HttpFileCollectionBase.Count > 0 && HttpFileCollectionBase[0].ContentLength < 1))
            {
                UploadError.Add("File does not exist!");
            }
            else
            {
                CreateDirectory(DataSource);
                var tmp = DataSource.Trim('/').Split('/');
                for (int i = 0; i < HttpFileCollectionBase.Count; i++)
                {
                    if (MaxFileCount > 0)
                    {
                        if (i >= MaxFileCount)
                        {
                            break;
                        }
                    }

                    var file = HttpFileCollectionBase[i];

                    if (Extension != null)
                    {
                        if (!file.FileName.IsExtension(Extension))
                        {
                            UploadError.Add("Extension:" + file.FileName);
                            continue;
                        }
                    }

                    if (file.ContentLength > 0)
                    {
                        if (Rename)
                        {
                            var fileName = (tmp[tmp.Length - 1] + "_" + Guid.NewGuid().ToString("N") + file.FileName.ToExtension()).ToLower();
                            UploadFile.Add(fileName);
                            UploadFileSource.Add(MapPath(DataSource) + fileName);
                        }
                        else
                        {
                            UploadFile.Add(file.FileName);
                            UploadFileSource.Add(MapPath(DataSource) + file.FileName);
                        }
                        file.SaveAs(UploadFileSource[i]);
                    }
                }
            }
            rs.Add("UploadFileSource", UploadFileSource);
            rs.Add("UploadFileSourceString", Helper.Strings.ArrayToString(UploadFileSource));
            rs.Add("UploadFile", UploadFile);
            rs.Add("UploadFileString", Helper.Strings.ArrayToString(UploadFile));
            rs.Add("UploadError", UploadError);
            return(rs);
        }
        public JsonResult Upload()
        {
            return(ExecuteFunctionRun(() =>
            {
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;//传输的文件
                ActionResult result = new ActionResult();
                BizRuleHanderViewModel model = new BizRuleHanderViewModel();

                if (files == null || files.Count == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.SelectFile";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }
                string fileType = Path.GetExtension(TrimHtml(Path.GetFileName(files[0].FileName))).ToLowerInvariant();
                if (!fileType.Replace(".", "").Equals("xml"))
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.FileMustIsXML";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                //将文件内容存放在缓存中
                string xmlStr = string.Empty;
                using (StreamReader sr = new StreamReader(files[0].InputStream))
                {
                    xmlStr = sr.ReadToEnd();
                }
                string newName = Guid.NewGuid().ToString() + fileType;

                model.FileName = newName;
                model.XMLString = xmlStr;

                //验证是否为伪造的xml文件
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(model.XMLString);
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.InvilidateFile";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                BizRuleTable BizRuleTable = ReadXmlFile(model); //从XML中读取服务名称和编码

                model.Code = BizRuleTable.Code;
                model.DisplayName = BizRuleTable.DisplayName;

                //界面控制,前台控制
                result.Success = true;
                result.Message = "";
                result.Extend = model;//返回上传的BizRule
                return Json(result, "text/html", JsonRequestBehavior.AllowGet);
            }));
        }
Exemplo n.º 4
0
        public JsonResult PublicToDingTalk(string appCode)
        {
            return(ExecuteFunctionRun(() =>
            {
                ActionResult result = new ActionResult();
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
                if (files == null || files.Count == 0)
                {
                    result.Success = false;
                    result.Message = "Apps.FileEmptyError";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                if (files[0].ContentLength > 100000)
                {
                    result.Success = false;
                    result.Message = "Apps.FileSizeError";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                var appmode = this.Engine.AppNavigationManager.GetApp(appCode);
                if (appmode == null)
                {
                    result.Success = false;
                    result.Message = "Apps.NotSaved";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                if (string.IsNullOrEmpty(appmode.DingTalkID))
                {
                    string mediaid = string.Empty;
                    if (files != null)
                    {
                        mediaid = this.Engine.DingTalkAdapter.UpdateFile(files[0].FileName, files[0].ContentType, files[0].ContentLength, GetBytesFromStream(files[0].InputStream));
                    }
                    //string homeUrl = Request.ApplicationPath + "/Mobile/index.html?showmenu=false&targer=appCenter&state=DefaultEngine&loginfrom=dingtalk&params={appCode:'" + appmode.AppCode + "'}";
                    string homeUrl = DingTalkPulishURL(appmode.AppCode);
                    var appresult = this.Engine.DingTalkAdapter.CreateMicroApp(mediaid, appmode.DisplayName, string.IsNullOrEmpty(appmode.Description)?appmode.DisplayName:appmode.Description, homeUrl, appmode.Url, "");
                    if (!string.IsNullOrEmpty(appresult.agentid))
                    {
                        appmode.DingTalkID = appresult.agentid;
                        this.Engine.AppNavigationManager.UpdateApp(appmode);
                        //权限
                        //var roles = this.Engine.FunctionAclManager.GetFunctionAclByCode(appmode.AppCode);
                    }
                    result.Success = appresult.errcode.Equals("0");
                    result.Message = appresult.errmsg;
                }
                else
                {
                    result.Success = false;
                    result.Message = "apps.wasPubliced";
                }

                return Json(result, JsonRequestBehavior.AllowGet);
            }));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 附件操作
        /// </summary>
        /// <param name="httpFiles"></param>
        /// <param name="fileId"></param>
        /// <param name="isTrans">回复或转发</param>
        /// <returns></returns>
        static List <Attachment> GetAttachs(System.Web.HttpFileCollectionBase httpFiles, string fileId, bool isTrans)
        {
            var relativePath = "";
            var path         = Sys.SysConstPool.SaveAttachPath(ref relativePath);
            var root         = Sys.SysConstPool.GetRoot;
            var list         = new List <Attachment>();

            if (isTrans && !fileId.IsNullOrEmpty())
            {
                var ids     = fileId.Split(',').Select(o => int.Parse(o)).ToList();
                var attachs = AttachService.FindList(o => ids.Contains(o.Id));
                foreach (var att in attachs)
                {
                    var      full = Path.Combine(root, att.SaveUrl);
                    FileInfo file = new FileInfo(full);
                    if (!file.Exists)
                    {
                        continue;
                    }
                    var destFileName = att.SaveUrl.Replace(file.Name, CommonRules.GUID + file.Extension);
                    var destFile     = Path.Combine(root, destFileName);
                    var info         = file.CopyTo(destFile);
                    list.Add(new Attachment()
                    {
                        SourceClassify = 3,
                        Title          = att.Title,
                        Size           = att.Size,
                        SaveUrl        = destFileName
                    });
                }
            }
            for (int i = 0; i < httpFiles.Count; i++)
            {
                var file = httpFiles[i];
                if (file.ContentLength <= 0)
                {
                    continue;
                }
                var    filename = CommonRules.GUID + Path.GetExtension(file.FileName);
                string fullname = path + filename;
                file.SaveAs(fullname);
                list.Add(new Attachment()
                {
                    SourceClassify = 3,
                    Title          = Path.GetFileName(file.FileName),
                    Size           = file.ContentLength / 1024,
                    SaveUrl        = relativePath + filename
                });
            }
            return(list);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 新增/修改单据
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="httpFiles"></param>
        /// <returns></returns>
        public static OpResult SaveOrUpdate(Receipts obj, System.Web.HttpFileCollectionBase httpFiles)
        {
            var re = new OpResult();

            if (IsExist(o => o.Number == obj.Number && o.Id != obj.Id))
            {
                re.Message = "已存在该单据编号";
                return(re);
            }
            var files        = new List <Attachment>();
            var relativePath = "";
            var path         = Sys.SysConstPool.SaveAttachPath(ref relativePath);

            for (int i = 0; i < httpFiles.Count; i++)
            {
                var file = httpFiles[i];
                if (file.ContentLength <= 0)
                {
                    continue;
                }
                var    filename = CommonRules.GUID + Path.GetExtension(file.FileName);
                string fullname = path + filename;
                file.SaveAs(fullname);
                files.Add(new Attachment()
                {
                    SourceClassify = 2,
                    Title          = Path.GetFileName(file.FileName),
                    Size           = file.ContentLength / 1024,
                    SaveUrl        = relativePath + filename
                });
            }
            obj.CompanyId = CommonService.CompanyId;
            if (string.IsNullOrWhiteSpace(obj.Id))
            {
                obj.Id        = CommonRules.GUID;
                obj.CreateUID = Pharos.Sys.SupplierUser.SupplierId;
                //obj.StoreId = CurrentUser.StoreId;
                obj.CreateDT    = DateTime.Now;
                obj.Source      = 2;
                obj.Attachments = files;
                re = Add(obj);
            }
            else
            {
                var sour = FindById(obj.Id);
                obj.ToCopyProperty(sour);
                sour.Attachments.AddRange(files);
                re = Update(sour);
            }
            return(re);
        }
Exemplo n.º 7
0
        public static OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var brandClass = SysDataDictService.FindList(o => o.DicPSN == (int)DicType.品牌分类 && o.CompanyId == CommonService.CompanyId);
                var otherClass = brandClass.FirstOrDefault(o => o.Title.StartsWith("其"));
                var brands     = GetAllProductBrands(null).ToList();
                var max        = SysDataDictService.GetMaxSN;
                var clsIdx     = Convert.ToInt32(fieldCols["ClassifyId"]) - 65;
                var titleIdx   = Convert.ToInt32(fieldCols["Title"]) - 65;
                count = dt.Rows.Count;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        var dr   = dt.Rows[i];
                        var text = dr[clsIdx].ToString();
                        if (text.IsNullOrEmpty())
                        {
                            continue;
                        }
                        var cls = brandClass.FirstOrDefault(o => o.Title == text);
                        if (cls != null)
                        {
                            dr[clsIdx] = cls.DicSN.ToString();
                        }
                        else
                        {
                            if (obj.RefCreate)
                            {
                                var data = new Sys.Entity.SysDataDictionary()
                                {
                                    DicPSN    = (int)DicType.品牌分类,
                                    DicSN     = max++,
                                    Status    = true,
                                    Title     = text,
                                    CompanyId = CommonService.CompanyId
                                };
                                SysDataDictService.Add(data);
                                brandClass.Add(data);
                                dr[clsIdx] = data.DicSN.ToString();
                            }
                            else if (otherClass != null)
                            {
                                dr[clsIdx] = otherClass.DicSN.ToString();
                            }
                            else
                            {
                                errLs.Add("品牌分类[" + text + "]不存在!");
                                dt.Rows.RemoveAt(i);//去除不导入
                                continue;
                            }
                        }
                        text = dr[titleIdx].ToString().Trim();
                        if (brands.Any(o => o.Title == text))
                        {
                            errLs.Add("品牌名称[" + text + "]已存在!");
                            dt.Rows.RemoveAt(i);//去除不导入
                        }
                        else
                        {
                            brands.Add(new ProductBrand()
                            {
                                Title = text
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("品牌分类处理失败!", e);
                    }
                }
                max = MaxSN;
                StringBuilder sb = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("insert into ");
                    sb.Append(obj.TableName);
                    sb.Append("(CompanyId,BrandSN,State,");
                    sb.Append(string.Join(",", fieldCols.Keys));
                    sb.Append(") values(");
                    sb.AppendFormat("{0},", obj.CompanyId);
                    sb.AppendFormat("{0},", max++);
                    sb.AppendFormat("1,");
                    foreach (var de in fieldCols)
                    {
                        var index = Convert.ToInt32(de.Value) - 65;
                        try
                        {
                            var text = dr[index].ToString();
                            sb.Append("'" + text + "',");
                        }
                        catch (Exception e)
                        {
                            throw new Exception("列选择超过范围!", e);
                        }
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append(");");
                }
                sb.Append(" commit tran");
                op.Successed = new Pharos.Logic.DAL.CommonDAL()._db.ExecuteNonQueryText(sb.ToString(), null) > 0;
                Log.WriteInsert("品牌导入", Sys.LogModule.档案管理);
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
Exemplo n.º 8
0
 public static System.Collections.Generic.Dictionary <string, object> Upload(System.Web.HttpFileCollectionBase HttpFileCollectionBase, string DataSource, bool Rename)
 {
     return(Upload(HttpFileCollectionBase, DataSource, Rename, null, 5));
 }
Exemplo n.º 9
0
        public string AddTextContent(Site site, TextFolder textFolder, System.Collections.Specialized.NameValueCollection values, System.Web.HttpFileCollectionBase files, IEnumerable <TextContent> categories, [System.Runtime.InteropServices.OptionalAttribute][System.Runtime.InteropServices.DefaultParameterValueAttribute("")] string userid, string vendor)
        {
            var schema = textFolder.GetSchema();

            var textContent = new TextContent(textFolder.Repository.Name, textFolder.SchemaName, textFolder.FullName);

            textContent = _textContentBinder.Bind(schema, textContent, values);

            if (!string.IsNullOrEmpty(values["UUID"]))
            {
                textContent.UUID = values["UUID"];
            }

            IncomeQueue incomeQueue = new IncomeQueue()
            {
                Message          = null,
                Object           = new Dictionary <string, object>(textContent),
                ObjectUUID       = textContent.IntegrateId,
                ObjectTitle      = textContent.GetSummary(),
                Vendor           = vendor,
                PublishingObject = PublishingObject.TextContent,
                Action           = PublishingAction.Publish,
                SiteName         = site.FullName,
                Status           = QueueStatus.Pending,
                UtcCreationDate  = DateTime.UtcNow,
                UtcProcessedTime = null,
                UUID             = Kooboo.UniqueIdGenerator.GetInstance().GetBase32UniqueId(10)
            };

            _incomeQueueProvider.Add(incomeQueue);

            return(textContent.IntegrateId);
        }
Exemplo n.º 10
0
        public OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var brandClass = DataDictRepository.GetQuery(o => o.DicPSN == 5).ToList();
                var otherClass = brandClass.FirstOrDefault(o => o.Title.StartsWith("其"));
                var brands     = GetList();
                var clsIdx     = Convert.ToInt32(fieldCols["ClassifyId"]) - 65;
                var titleIdx   = Convert.ToInt32(fieldCols["Title"]) - 65;
                count = dt.Rows.Count;
                var max = DataDictRepository.GetQuery().Max(o => o.DicSN);
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        var dr   = dt.Rows[i];
                        var text = dr[clsIdx].ToString();
                        if (text.IsNullOrEmpty())
                        {
                            continue;
                        }
                        var cls = brandClass.FirstOrDefault(o => o.Title == text);
                        if (cls != null)
                        {
                            dr[clsIdx] = cls.DicSN.ToString();
                        }
                        else
                        {
                            if (obj.RefCreate)
                            {
                                var data = new SysDataDictionary
                                {
                                    DicPSN    = 5,
                                    Status    = true,
                                    Title     = text,
                                    DicSN     = max++,
                                    CreateDT  = DateTime.Now,
                                    CreateUID = CurrentUser.UID
                                };
                                DataDictRepository.Add(data);
                                brandClass.Add(data);
                                dr[clsIdx] = data.DicSN.ToString();
                            }
                            else if (otherClass != null)
                            {
                                dr[clsIdx] = otherClass.DicSN.ToString();
                            }
                            else
                            {
                                errLs.Add("行业分类[" + text + "]不存在!");
                                dt.Rows.RemoveAt(i);//去除不导入
                                continue;
                            }
                        }
                        text = dr[titleIdx].ToString().Trim();
                        if (brands.Any(o => o.Title == text))
                        {
                            errLs.Add("品牌名称[" + text + "]已存在!");
                            dt.Rows.RemoveAt(i);//去除不导入
                        }
                        else
                        {
                            brands.Add(new ProductBrand()
                            {
                                Title = text
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("品牌分类处理失败!", e);
                    }
                }
                var           maxsn = BrandRepository.GetQuery().Max(o => (int?)o.BrandSN).GetValueOrDefault();
                StringBuilder sb    = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("insert into ");
                    sb.Append(obj.TableName);
                    sb.Append("(BrandSN,State,Source,");
                    sb.Append(string.Join(",", fieldCols.Keys));
                    sb.Append(") values(");
                    sb.AppendFormat("{0},", ++maxsn);
                    sb.AppendFormat("1,0,");
                    foreach (var de in fieldCols)
                    {
                        var index = Convert.ToInt32(de.Value) - 65;
                        try
                        {
                            var text = dr[index].ToString();
                            sb.Append("'" + text + "',");
                        }
                        catch (Exception e)
                        {
                            throw new Exception("列选择超过范围!", e);
                        }
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append(");");
                }
                sb.Append(" commit tran");
                if (dt.Rows.Count > 0)
                {
                    op.Successed = new DBHelper().ExecuteNonQueryText(sb.ToString(), null) > 0;
                    LogEngine.WriteInsert("品牌导入", LogModule.档案管理);
                }
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                LogEngine.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
Exemplo n.º 11
0
 public static System.Collections.Generic.Dictionary <string, object> UploadImages(System.Web.HttpFileCollectionBase HttpFileCollectionBase, string DataSource, bool Rename, int MaxFileCount)
 {
     return(Upload(HttpFileCollectionBase, DataSource, Rename, new[] { ".jpg", ".jpeg", ".png", ".gif", ".tiff", ".bmp" }, MaxFileCount));
 }
Exemplo n.º 12
0
        public static OpResult InboundImport(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;
            var list  = new List <InboundList>();

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var supplierId       = System.Web.HttpContext.Current.Request["SupplierID"];
                var storeId          = System.Web.HttpContext.Current.Request["StoreId"];
                var supplierBarcodes = new List <string>();
                var storeBarcodes    = new List <string>();
                var products         = new List <VwProduct>();
                if (!supplierId.IsNullOrEmpty())
                {
                    var bars = BaseService <ProductMultSupplier> .FindList(o => o.SupplierId == supplierId).Select(o => o.Barcode).Distinct().ToList();

                    var pros = BaseService <VwProduct> .FindList(o => o.SupplierId == supplierId || bars.Contains(o.Barcode));

                    products.AddRange(pros);
                    supplierBarcodes = pros.Select(o => o.Barcode).ToList();
                    supplierBarcodes.AddRange(pros.Where(o => !o.Barcodes.IsNullOrEmpty()).SelectMany(o => o.Barcodes.Split(',')));
                }
                if (!storeId.IsNullOrEmpty())
                {
                    var ware = WarehouseService.Find(o => o.StoreId == storeId && o.CompanyId == CommonService.CompanyId);
                    if (ware != null)
                    {
                        var categorySNs = ware.CategorySN.Split(',').Select(o => int.Parse(o)).ToList();
                        var childs      = ProductCategoryService.GetChildSNs(categorySNs);
                        var pros        = BaseService <VwProduct> .FindList(o => o.CompanyId == CommonService.CompanyId && childs.Contains(o.CategorySN));

                        storeBarcodes = pros.Select(o => o.Barcode).ToList();
                        storeBarcodes.AddRange(pros.Where(o => !o.Barcodes.IsNullOrEmpty()).SelectMany(o => o.Barcodes.Split(',')));
                        products.AddRange(pros);
                    }
                }
                var barcodeIdx  = fieldCols.GetValue("Barcode").ToType <int>() - 65;
                var buyPriceIdx = fieldCols.GetValue("BuyPrice").ToType <int>() - 65;
                var numberIdx   = fieldCols.GetValue("InboundNumber").ToType <int>() - 65;
                var proDateIdx  = fieldCols.GetValue("ProducedDate").ToType <int>() - 65;
                var giftIdx     = fieldCols.GetValue("IsGift").ToType <int>() - 65;
                var memoIdx     = fieldCols.GetValue("Memo").ToType <int>() - 65;
                count = dt.Rows.Count;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var pos     = i + obj.MinRow;
                    var dr      = dt.Rows[i];
                    var barcode = dr.GetValue(barcodeIdx).ToString().Trim();
                    if (barcode.IsNullOrEmpty())
                    {
                        errLs.Add("行号[" + pos + "]条码为空!");
                        continue;
                    }
                    if (!supplierBarcodes.Any(o => o == barcode))
                    {
                        errLs.Add("行号[" + pos + "]该供应单位下无此条码!");
                        continue;
                    }
                    if (!storeBarcodes.Any(o => o == barcode))
                    {
                        errLs.Add("行号[" + pos + "]该门店下无此条码!");
                        continue;
                    }
                    var buyPrice = dr.GetValue(buyPriceIdx).ToType <decimal?>();
                    if (!buyPrice.HasValue)
                    {
                        errLs.Add("行号[" + pos + "]该条码进价为空!");
                        continue;
                    }
                    var number = dr.GetValue(numberIdx).ToType <decimal?>();
                    if (!number.HasValue)
                    {
                        errLs.Add("行号[" + pos + "]该条码入库数量为空!");
                        continue;
                    }
                    var      gift    = dr.GetValue(giftIdx).ToString();
                    var      proDate = dr.GetValue(proDateIdx).ToString().Trim();
                    DateTime t       = DateTime.Now;
                    if (!proDate.IsNullOrEmpty() && DateTime.TryParse(proDate, out t))
                    {
                        proDate = t.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        proDate = string.Empty;
                    }
                    var pro = products.FirstOrDefault(o => o.Barcode == barcode || ("," + o.Barcodes + ",").Contains("," + barcode + ","));
                    list.Add(new InboundList()
                    {
                        Barcode       = barcode,
                        ProductTitle  = pro.Title,
                        BuyPrice      = buyPrice.Value,
                        InboundNumber = number.Value,
                        Unit          = pro.SubUnit,
                        ProducedDate  = proDate,
                        SysPrice      = pro.SysPrice,
                        Memo          = dr.GetValue(memoIdx).ToString(),
                        IsGift        = (short)(gift == "赠品"?1:0)
                    });
                }
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count, data: list, isSuccess: false));
        }
Exemplo n.º 13
0
 public static System.Collections.Generic.Dictionary <string, object> Upload(System.Web.HttpFileCollectionBase HttpFileCollectionBase, string DataSource, string[] Extension)
 {
     return(Upload(HttpFileCollectionBase, DataSource, true, Extension, 5));
 }
        public JsonResult Save(WorkflowClauseViewModel model)
        {
            return(ExecuteFunctionRun(() =>
            {
                ActionResult result = new ActionResult(false, "");
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
                WorkflowTemplate.WorkflowClause SelectedClause = this.Engine.WorkflowManager.GetClause(model.WorkflowCode);
                // 检查输入
                int sortKey = model.SortKey;

                // 更新模板
                SelectedClause.WorkflowName = model.DisplayName;
                SelectedClause.SortKey = sortKey;

                // 移动办公设置
                SelectedClause.MobileStart = model.MobileStart;

                // 流水号编码
                SelectedClause.SequenceCode = model.SequenceCode ?? "";
                // 流水号重置方式
                SelectedClause.SeqNoResetType = (Instance.SequenceNoResetType)Enum.Parse(typeof(Instance.SequenceNoResetType), model.SeqNoResetType);

                SelectedClause.State = model.IsActive ? WorkflowTemplate.WorkflowState.Active : OThinker.H3.WorkflowTemplate.WorkflowState.Inactive;

                SelectedClause.CalendarId = model.WorkCalendar;
                //异常管理员
                SelectedClause.ExceptionManager = model.ExceptionManager;

                //旧图标地址
                string oldImagePath = SelectedClause.IconFileName;
                // 设置图标
                if (files.Count > 0 && files[0].FileName.Length > 0)
                {
                    var fileIcon = files[0];
                    if (!System.IO.Directory.Exists(WorkflowIconRootPath))
                    {
                        System.IO.Directory.CreateDirectory(WorkflowIconRootPath);
                    }

                    string fileExt = System.IO.Path.GetExtension(fileIcon.FileName);
                    if (!(fileExt == ".png" || fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp"))
                    {
                        result.Message = "WorkflowSetting.WorkflowTemplateSetting_ImageFormat";
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }

                    //记录旧图标
                    oldImagePath = SelectedClause.IconFileName;
                    SelectedClause.IconFileName = Guid.NewGuid().ToString().ToLower() + fileExt;

                    fileIcon.SaveAs(WorkflowIconRootPath + "/" + SelectedClause.IconFileName);
                }

                //设置默认版本号
                int defaultVersion = SelectedClause.DefaultVersion;
                int.TryParse(model.WorkflowVersion, out defaultVersion);
                SelectedClause.DefaultVersion = defaultVersion;

                long result2 = this.Engine.WorkflowManager.UpdateClause(SelectedClause);
                if (result2 != ErrorCode.SUCCESS)
                {
                    result.Message = "msgGlobalString.UpdateFailed";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    //删除旧图标
                    try
                    {
                        if (oldImagePath != SelectedClause.IconFileName)
                        {
                            System.IO.File.Delete(WorkflowIconRootPath + "/" + oldImagePath);
                        }
                    }
                    catch { }

                    // 通知结果
                    result.Message = "msgGlobalString.SaveSucced";
                    result.Success = true;
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }
            }));
        }
Exemplo n.º 15
0
        public static OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName, short businessType)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var supplierClass = SysDataDictService.FindList(o => o.DicPSN == (int)DicType.供应商分类);
                var otherClass    = supplierClass.FirstOrDefault(o => o.Title.StartsWith("其"));
                var suppliers     = GetList();
                var users         = UserInfoService.GetList();
                var max           = SysDataDictService.GetMaxSN;
                var clsIdx        = Convert.ToInt32(fieldCols["ClassifyId"]) - 65;
                var titleIdx      = Convert.ToInt32(fieldCols["Title"]) - 65;
                var fulltitleIdx  = Convert.ToInt32(fieldCols["FullTitle"]) - 65;
                var linkmanIdx    = Convert.ToInt32(fieldCols["Linkman"]) - 65;
                var designeeIdx   = Convert.ToInt32(fieldCols["Designee"]) - 65;
                count = dt.Rows.Count;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        var dr   = dt.Rows[i];
                        var text = dr[clsIdx].ToString();
                        if (text.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + i + "]供应商分类为空!");
                            dt.Rows.RemoveAt(i);//去除不导入
                            continue;
                        }
                        var cls = supplierClass.FirstOrDefault(o => o.Title == text);
                        if (cls != null)
                        {
                            dr[clsIdx] = cls.DicSN.ToString();
                        }
                        else
                        {
                            if (obj.RefCreate)
                            {
                                var data = new Sys.Entity.SysDataDictionary()
                                {
                                    DicPSN    = (int)DicType.供应商分类,
                                    DicSN     = max++,
                                    Status    = true,
                                    Title     = text,
                                    CompanyId = CommonService.CompanyId
                                };
                                SysDataDictService.Add(data);
                                supplierClass.Add(data);
                                dr[clsIdx] = data.DicSN.ToString();
                            }
                            else if (otherClass != null)
                            {
                                dr[clsIdx] = otherClass.DicSN.ToString();
                            }
                            else
                            {
                                errLs.Add("供应商分类[" + text + "]不存在!");
                                dt.Rows.RemoveAt(i);//去除不导入
                                continue;
                            }
                        }
                        text = dr[designeeIdx].ToString();
                        var user = users.FirstOrDefault(o => o.FullName == text);
                        if (user != null)
                        {
                            dr[designeeIdx] = user.UID;
                        }
                        else
                        {
                            errLs.Add("指派人[" + text + "]不存在!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }
                        text = dr[titleIdx].ToString().Trim();
                        var fulltext = dr[fulltitleIdx].ToString().Trim();
                        var linkman  = dr[linkmanIdx].ToString().Trim();
                        if (text.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + text + "]简称为空!");
                            dt.Rows.RemoveAt(i);
                        }
                        else if (fulltext.IsNullOrEmpty())
                        {
                            errLs.Add("简称[" + text + "]全称为空!");
                            dt.Rows.RemoveAt(i);
                        }
                        else if (linkman.IsNullOrEmpty())
                        {
                            errLs.Add("简称[" + text + "]联系人为空!");
                            dt.Rows.RemoveAt(i);
                        }
                        else if (suppliers.Any(o => o.Title == text))
                        {
                            errLs.Add("简称[" + text + "]已存在!");
                            dt.Rows.RemoveAt(i);
                        }
                        else if (suppliers.Any(o => o.FullTitle == fulltext))
                        {
                            errLs.Add("全称[" + fulltext + "]已存在!");
                            dt.Rows.RemoveAt(i);
                        }
                        else
                        {
                            suppliers.Add(new Supplier()
                            {
                                Title     = text,
                                FullTitle = fulltext
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("供应商分类处理失败!", e);
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("insert into Supplier");
                    sb.Append("(CompanyId,BusinessType,Id,");
                    sb.Append(string.Join(",", fieldCols.Keys));
                    sb.Append(") values(");
                    sb.AppendFormat("{0},", obj.CompanyId);
                    sb.AppendFormat(businessType + ",");
                    sb.AppendFormat("'{0}',", CommonRules.GUID);
                    foreach (var de in fieldCols)
                    {
                        var index = Convert.ToInt32(de.Value) - 65;
                        try
                        {
                            var text = dr[index].ToString();
                            sb.Append("'" + text + "',");
                        }
                        catch (Exception e)
                        {
                            throw new Exception("列选择超过范围!", e);
                        }
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append(");");
                }
                sb.Append(" commit tran");
                op.Successed = new Pharos.Logic.DAL.CommonDAL()._db.ExecuteNonQueryText(sb.ToString(), null) > 0;
                log.WriteInsert(obj.TableName == "Supplier" ? "供应商导入" : "批发商导入", Pharos.Sys.LogModule.档案管理);
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
Exemplo n.º 16
0
        /// <summary>
        /// 发送,草稿,回复,转发
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="httpFiles">附件</param>
        /// <param name="fileId">原存在附件ID</param>
        /// <returns></returns>
        public static OpResult SendMail(SysMailSender obj, System.Web.HttpFileCollectionBase httpFiles, string fileId)
        {
            var op = new OpResult();

            try
            {
                var mailReceives = new List <SysMailReceive>();
                obj.ReceiverCodes.IsNullThrow("收件人不能空!");
                var receiverIds = obj.ReceiverCodes.Split(';');
                var createDate  = DateTime.Now;
                var sendCode    = Sys.CurrentUser.UserName;
                var sendName    = Sys.CurrentUser.FullName;
                foreach (var o in receiverIds)
                {
                    if (o.IsNullOrEmpty())
                    {
                        continue;
                    }
                    string uid = "", uname = "";
                    if (o.Contains("("))
                    {
                        uid   = o.Substring(o.LastIndexOf("(") + 1).TrimEnd(')');
                        uname = o.Substring(0, o.IndexOf("("));
                    }
                    else
                    {
                        var user = GetUser(o);
                        if (user == null)
                        {
                            continue;
                        }
                        uid   = user.UserCode.ToString();
                        uname = user.FullName;
                    }
                    var rece = new SysMailReceive();
                    obj.ToCopyProperty(rece);
                    rece.ReceiveCode = uid;
                    rece.ReceiveName = uname;
                    rece.SenderCode  = sendCode;
                    rece.SenderName  = sendName;
                    rece.State       = 0;
                    rece.Type        = 1;
                    rece.Id          = CommonRules.GUID;
                    rece.CreateDT    = createDate;
                    rece.BatchNo     = createDate.ToString("yyyyMMddHHmmssfff");
                    mailReceives.Add(rece);
                }
                if (!obj.CopytoCodes.IsNullOrEmpty())
                {
                    var copytoIds = obj.CopytoCodes.Split(';');
                    foreach (var o in copytoIds)
                    {
                        if (o.IsNullOrEmpty())
                        {
                            continue;
                        }
                        string uid = "", uname = "";
                        if (o.Contains("("))
                        {
                            uid   = o.Substring(o.LastIndexOf("(") + 1).TrimEnd(')');
                            uname = o.Substring(0, o.IndexOf("("));
                        }
                        else
                        {
                            var user = GetUser(o);
                            if (user == null)
                            {
                                continue;
                            }
                            uid   = user.UserCode.ToString();
                            uname = user.FullName;
                        }
                        var rece = new SysMailReceive();
                        obj.ToCopyProperty(rece);
                        rece.ReceiveCode = uid;
                        rece.ReceiveName = uname;
                        rece.SenderCode  = sendCode;
                        rece.SenderName  = sendName;
                        rece.State       = 0;
                        rece.Type        = 2;
                        rece.Id          = CommonRules.GUID;
                        rece.CreateDT    = createDate;
                        rece.BatchNo     = createDate.ToString("yyyyMMddHHmmssfff");
                        mailReceives.Add(rece);
                    }
                }
                if (obj.State == 1)
                {
                    foreach (var rece in mailReceives)
                    {
                        rece.Attachments = GetAttachs(httpFiles, fileId, obj.Id.IsNullOrEmpty() && !obj.BatchNo.IsNullOrEmpty());
                    }
                }
                obj.Attachments = GetAttachs(httpFiles, fileId, obj.Id.IsNullOrEmpty() && !obj.BatchNo.IsNullOrEmpty());
                obj.CompanyId   = CommonService.CompanyId;
                if (obj.Id.IsNullOrEmpty())
                {
                    obj.BatchNo    = createDate.ToString("yyyyMMddHHmmssfff");
                    obj.Id         = CommonRules.GUID;
                    obj.CreateDT   = createDate;
                    obj.SenderCode = sendCode;
                    obj.SenderName = sendName;
                    if (obj.State == 1)//发送
                    {
                        Add(obj, false);
                        op = BaseService <SysMailReceive> .AddRange(mailReceives, true);
                    }
                    else
                    {
                        op = Add(obj);
                    }

                    #region 写入日志
                    string StateTitle = obj.State == 1 ? "已发送" : "存草稿";
                    string msg        = obj.State == 1 ? "成功发送邮件!" : "成功保存草稿到发件箱!";
                    var    module     = Pharos.Sys.LogModule.邮件管理;
                    if (op.Successed)
                    {
                        string copyCodes = string.IsNullOrEmpty(obj.CopytoCodes) ? "" : (",抄送人=" + obj.CopytoCodes);
                        msg += "<br />Id=" + obj.Id + ",";
                        msg += "<br />收件人=" + obj.ReceiverCodes + copyCodes + ",状态=" + StateTitle + ",主题=" + obj.Title + ",批次=" + obj.BatchNo + "。";
                    }
                    else
                    {
                        msg = obj.State == 1 ? "发送邮件失败!" : "保存草稿到发件箱失败!";
                    }
                    log.WriteInsert(msg, module);
                    #endregion
                }
                else//草稿时
                {
                    var  resour        = CurrentRepository.QueryEntity.Include(o => o.Attachments).SingleOrDefault(o => o.Id == obj.Id);
                    var  isUpdateRec   = obj.ReceiverCodes != resour.ReceiverCodes;
                    var  isUpdateCop   = obj.CopytoCodes != resour.CopytoCodes;
                    var  isUpdateState = obj.State != resour.State;
                    var  isUpdateTitle = obj.Title != resour.Title;
                    var  isUpdateBody  = obj.Body != resour.Body;
                    bool isUpdate      = isUpdateRec || isUpdateCop || isUpdateState || isUpdateTitle || isUpdateBody;
                    obj.ToCopyProperty(resour);
                    foreach (var att in obj.Attachments)
                    {
                        if (!resour.Attachments.Any(o => o.Title == att.Title))
                        {
                            resour.Attachments.Add(att);
                        }
                    }
                    if (obj.State == 1)//发送
                    {
                        Update(resour, false);
                        op = BaseService <SysMailReceive> .AddRange(mailReceives, true);
                    }
                    else
                    {
                        op = Update(resour);
                    }

                    #region 写入日志
                    string StateTitle = obj.State == 1 ? "已发送" : "存草稿";
                    string msg        = obj.State == 1 ? "成功发送邮件!" : "成功修改草稿!";
                    var    module     = Pharos.Sys.LogModule.邮件管理;
                    if (op.Successed)
                    {
                        int n = 0;
                        if (isUpdate)
                        {
                            msg += "<br />Id=" + obj.Id + ",<br />";
                            if (isUpdateState)
                            {
                                msg += "状态由草稿改为已发送";
                                n    = n + 1;
                            }
                            if (isUpdateRec)
                            {
                                msg += n > 0 ? ",收件人=" + obj.ReceiverCodes : "收件人=" + obj.ReceiverCodes;
                                n    = n + 1;
                            }
                            if (isUpdateCop)
                            {
                                msg += n > 0 ? ",抄送人=" + obj.CopytoCodes : "抄送人=" + obj.CopytoCodes;
                                n    = n + 1;
                            }
                            if (isUpdateTitle)
                            {
                                msg += n > 0 ? ",主题=" + obj.Title : "主题=" + obj.Title;
                                n    = n + 1;
                            }
                            if (isUpdateBody)
                            {
                                msg += n > 0 ? ",正文=" + obj.Body : "正文=" + obj.Body;
                            }
                            msg += "。";
                            log.WriteUpdate(msg, module);
                        }
                    }
                    else
                    {
                        msg = obj.State == 1 ? "发送邮件失败(从发件箱的草稿发送)!" : "修改草稿失败!";
                        log.WriteUpdate(msg, module);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                op.Message = ex.Message;
                Log.WriteError(ex);
            }
            return(op);
        }
Exemplo n.º 17
0
        /// <summary>
        /// 上传主数据文件
        /// </summary>
        /// <returns></returns>
        public JsonResult Upload()
        {
            return(ExecuteFunctionRun(() =>
            {
                ActionResult result = new ActionResult(true);
                BizMasterDataImportViewModel model = new BizMasterDataImportViewModel();
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;//传输的文件

                if (files == null || files.Count == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.SelectFile";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }
                var file = files[0];

                string fileType = Path.GetExtension(TrimHtml(Path.GetFileName(file.FileName))).ToLowerInvariant();
                if (!fileType.Replace(".", "").Equals("xml"))
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.FileMustIsXML";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                string xmlStr = string.Empty;
                using (StreamReader sr = new StreamReader(file.InputStream))
                {
                    xmlStr = sr.ReadToEnd();
                }
                string newName = Guid.NewGuid().ToString() + fileType;
                model.XmlSessionName = newName;
                //将文件内容存放在缓存中
                this.Session[newName] = xmlStr;

                //验证是否为伪造的xml文件
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(this.Session[model.XmlSessionName].ToString());
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.InvilidateFile";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                try
                {
                    ReadXmlFile(model);
                }
                catch
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.InvilidateFile";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }


                //界面控制
                result.Success = true;
                result.Message = "";
                result.Extend = model;
                return Json(result, "text/html", JsonRequestBehavior.AllowGet);
            }));
        }
Exemplo n.º 18
0
        /// <summary>
        /// 上传模板
        /// </summary>
        /// <param name="ParentCode"></param>
        /// <returns></returns>
        public JsonResult Upload(string ParentCode)
        {
            return(ExecuteFunctionRun(() =>
            {
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;//传输的文件
                ActionResult result = new ActionResult(false, "");
                WorkflowPackageImportViewModel model = new WorkflowPackageImportViewModel();

                if (files == null || files.Count == 0 || string.IsNullOrEmpty(files[0].FileName))
                {
                    result.Message = "WorkflowPackageImport.MasterData_Mssg10";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                string fileType = Path.GetExtension(TrimHtml(Path.GetFileName(files[0].FileName))).ToLowerInvariant();
                if (!fileType.Replace(".", "").Equals("xml"))
                {
                    result.Message = "WorkflowPackageImport.MasterData_Mssg11";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                int FileLen = files[0].ContentLength;
                byte[] input = new byte[FileLen];
                System.IO.Stream UpLoadStream = files[0].InputStream;

                UpLoadStream.Read(input, 0, FileLen);
                UpLoadStream.Position = 0;
                System.IO.StreamReader sr = new System.IO.StreamReader(UpLoadStream);

                string xmlStr = sr.ReadToEnd();
                sr.Close();

                //保存到服务器上
                string newName = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + fileType;

                //验证是否为伪造的xml文件
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xmlStr);
                }
                catch (Exception ex)
                {
                    result.Message = "WorkflowPackageImport.MasterData_Mssg11";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                model.ParentCode = ParentCode;

                model.XMLString = Guid.NewGuid().ToString();//Session Name

                Session[model.XMLString] = xmlStr;

                try
                {
                    ReadXmlFile(model);
                }
                catch
                {
                    result.Message = "WorkflowPackageImport.MasterData_Mssg11";
                    return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                }

                //oldCOde 存储导入时修改前的编码
                model.WorkflowPackage = new ItemDetail {
                    CodeType = FunctionNodeType.BizWorkflowPackage.ToString(), Name = PackageName, Code = PackageCode, OldCode = PackageCode, Index = 1
                };
                model.BizSchema = new ItemDetail {
                    CodeType = FunctionNodeType.BizObject.ToString(), Name = BizObjectSchema.DisplayName, Code = BizObjectSchema.SchemaCode, OldCode = BizObjectSchema.SchemaCode, Index = 1
                };


                if (BizSheets.Count > 0)
                {
                    List <ItemDetail> listSheets = new List <ItemDetail>();
                    int index = 1;
                    foreach (BizSheet sheet in BizSheets)
                    {
                        ItemDetail dl = new ItemDetail();
                        dl.Code = sheet.SheetCode;
                        dl.OldCode = sheet.SheetCode;
                        dl.Name = sheet.DisplayName;
                        dl.Index = index;
                        dl.CodeType = FunctionNodeType.BizSheet.ToString();
                        index++;

                        listSheets.Add(dl);
                    }

                    model.BizSheets = listSheets;
                }

                if (WorkflowTemplates.Count > 0)
                {
                    List <ItemDetail> listflow = new List <ItemDetail>();
                    int index = 1;
                    foreach (DraftWorkflowTemplate flow in WorkflowTemplates)
                    {
                        ItemDetail dl = new ItemDetail();
                        dl.Code = flow.WorkflowCode;
                        dl.OldCode = flow.WorkflowCode;
                        dl.Name = WorkflowNames.ContainsKey(flow.WorkflowCode) ? WorkflowNames[flow.WorkflowCode] : flow.WorkflowCode;
                        dl.Index = index;
                        dl.CodeType = FunctionNodeType.BizWorkflow.ToString();
                        index++;

                        listflow.Add(dl);
                    }

                    model.WorkFlows = listflow;
                }

                if (this.bizQueryList != null && this.bizQueryList.Count > 0)
                {
                    List <ItemDetail> listQuery = new List <ItemDetail>();
                    int index = 1;
                    foreach (BizQuery query in this.bizQueryList)
                    {
                        ItemDetail dl = new ItemDetail();
                        dl.Code = query.QueryCode;
                        dl.OldCode = query.QueryCode;
                        dl.Name = query.DisplayName;
                        dl.Index = index;
                        dl.CodeType = BizQueryCode;
                        index++;

                        listQuery.Add(dl);
                    }
                    model.QueryList = listQuery;
                }

                result.Success = true;
                result.Message = "";
                result.Extend = model;
                return Json(result, "text/html", JsonRequestBehavior.AllowGet);
                //BuildInterface();
            }));
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="httpFiles"></param>
        /// <param name="fieldName"></param>
        /// <param name="columnName"></param>
        /// <param name="fieldCols">字段和对应列</param>
        /// <param name="dt">导入表数据</param>
        /// <returns></returns>
        public static OpResult ImportSet(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName, ref Dictionary <string, char> fieldCols, ref System.Data.DataTable dt)
        {
            var op = new OpResult();

            if (httpFiles.Count <= 0 || httpFiles[0].ContentLength <= 0)
            {
                op.Message = "请先选择Excel文件";
                return(op);
            }
            var stream = httpFiles[0].InputStream;
            var ext    = httpFiles[0].FileName.Substring(httpFiles[0].FileName.LastIndexOf("."));

            if (!(ext.Equals(".xls", StringComparison.CurrentCultureIgnoreCase) ||
                  ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)))
            {
                op.Message = "请先选择Excel文件";
                return(op);
            }
            var path     = "";
            var fullPath = Utility.Helpers.FileHelper.SaveAttachPath(ref path, "temps");

            httpFiles[0].SaveAs(fullPath + httpFiles[0].FileName);
            fieldCols = fieldCols ?? new Dictionary <string, char>();
            if (!fieldName.IsNullOrEmpty() && !columnName.IsNullOrEmpty())
            {
                var fields  = fieldName.Split(',');
                var columns = columnName.Split(',');
                if (fields.Length != columns.Length)
                {
                    op.Message = "配置的字段和列数不一致!";
                    return(op);
                }
                for (var i = 0; i < fields.Length; i++)
                {
                    if (columns[i].IsNullOrEmpty())
                    {
                        continue;
                    }
                    fieldCols[fields[i]] = Convert.ToChar(columns[i]);
                }
                //if (fieldCols.Values.Distinct().Count() != fieldCols.Values.Count())
                //{
                //    op.Message = "配置的列存在重复!";
                //    return op;
                //}
                obj.FieldJson = fieldCols.Select(o => new { o.Key, o.Value }).ToJson();
            }
            if (obj.Id == 0)
            {
                if (!BaseService <ImportSet> .IsExist(o => o.TableName == obj.TableName && o.CompanyId == obj.CompanyId))
                {
                    op = BaseService <ImportSet> .Add(obj);
                }
                else
                {
                    op.Successed = true;
                }
            }
            else
            {
                var res = BaseService <ImportSet> .FindById(obj.Id);

                obj.ToCopyProperty(res);
                op = BaseService <ImportSet> .Update(res);
            }
            if (!op.Successed)
            {
                return(op);
            }

            dt = new ExportExcel().ToDataTable(stream, minRow: obj.MinRow, maxRow: obj.MaxRow.GetValueOrDefault());
            if (dt == null || dt.Rows.Count <= 0)
            {
                op.Message   = "无数据,无法导入!";
                op.Successed = false;
                return(op);
            }
            #region 去掉空格
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.DataType == typeof(string))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (!(dr[dc] is DBNull))
                        {
                            dr[dc] = dr[dc].ToString().Trim();
                        }
                    }
                }
            }
            #endregion
            #region 允许配置在同一列
            var cols = fieldCols.GroupBy(o => o.Value).Where(o => o.Count() > 1).ToList();//取重复列
            foreach (var item in cols)
            {
                System.Diagnostics.Debug.WriteLine(item.Key);//重复列value
                var idx = Convert.ToInt32(item.Key) - 65;
                foreach (var subitem in item)
                {
                    System.Diagnostics.Debug.WriteLine(subitem.Key);//重复列key
                    var lastValue = Convert.ToChar(fieldCols.Values.OrderBy(o => o).LastOrDefault() + 1);
                    if (dt.Columns[idx].CloneTo(subitem.Key))
                    {
                        fieldCols[subitem.Key] = lastValue;
                    }
                }
            }
            #endregion

            op.Successed = true;
            return(op);
        }
Exemplo n.º 20
0
        public static OpResult OutboundImport(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;
            var list  = new List <OutboundList>();

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var storeId  = System.Web.HttpContext.Current.Request["StoreId"];
                var products = new List <VwProduct>();
                if (!storeId.IsNullOrEmpty())
                {
                    var ware = WarehouseService.Find(o => o.StoreId == storeId && o.CompanyId == CommonService.CompanyId);
                    if (ware != null)
                    {
                        var categorySNs = ware.CategorySN.Split(',').Select(o => int.Parse(o)).ToList();
                        var childs      = ProductCategoryService.GetChildSNs(categorySNs);
                        var pros        = BaseService <VwProduct> .FindList(o => o.CompanyId == CommonService.CompanyId && childs.Contains(o.CategorySN));

                        products.AddRange(pros);
                    }
                }
                var barcodeIdx  = fieldCols.GetValue("Barcode").ToType <int>() - 65;
                var outPriceIdx = fieldCols.GetValue("OutPrice").ToType <int>() - 65;
                var numberIdx   = fieldCols.GetValue("OutboundNumber").ToType <int>() - 65;
                var memoIdx     = fieldCols.GetValue("Memo").ToType <int>() - 65;
                count = dt.Rows.Count;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var pos     = i + obj.MinRow;
                    var dr      = dt.Rows[i];
                    var barcode = dr.GetValue(barcodeIdx).ToString().Trim();
                    if (barcode.IsNullOrEmpty())
                    {
                        errLs.Add("行号[" + pos + "]条码为空!");
                        continue;
                    }
                    var pro = products.FirstOrDefault(o => o.Barcode == barcode || ("," + o.Barcodes + ",").Contains("," + barcode + ","));
                    if (pro == null)
                    {
                        errLs.Add("行号[" + pos + "]该门店下无此条码!");
                        continue;
                    }
                    var outPrice = dr.GetValue(outPriceIdx).ToType <decimal?>();
                    if (!outPrice.HasValue && outPriceIdx >= 0)
                    {
                        errLs.Add("行号[" + pos + "]该条码价格为空!");
                        continue;
                    }
                    var number = dr.GetValue(numberIdx).ToType <decimal?>();
                    if (!number.HasValue)
                    {
                        errLs.Add("行号[" + pos + "]该条码出库数量为空!");
                        continue;
                    }

                    list.Add(new OutboundList()
                    {
                        Barcode        = barcode,
                        ProductTitle   = pro.Title,
                        BuyPrice       = pro.BuyPrice,
                        OutboundNumber = number.Value,
                        Unit           = pro.SubUnit,
                        SysPrice       = pro.SysPrice,
                        OutPrice       = outPrice ?? pro.SysPrice,
                        Memo           = dr.GetValue(memoIdx).ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count, data: list, isSuccess: false));
        }
Exemplo n.º 21
0
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="httpFiles"></param>
        /// <param name="fieldName"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>

        public OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }

                //数据字典
                var dataDictionary = SysDataDictionaryRepository.GetQuery();

                //设备分类名称
                var CIdx = Convert.ToInt32(fieldCols["CategoryId"]) - 65;
                //设备名称
                var TitleIdx = Convert.ToInt32(fieldCols["Title"]) - 65;
                //品牌
                var BrandIdx = Convert.ToInt32(fieldCols["Brand"]) - 65;
                //型号
                var SpecIdx = Convert.ToInt32(fieldCols["Spec"]) - 65;

                count = dt.Rows.Count;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        var dr = dt.Rows[i];
                        #region 验证
                        //设备分类名称
                        var text = dr[CIdx].ToString().Trim();
                        if (text.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + (i + 1) + "]设备分类为空!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }
                        var dd = dataDictionary.Where(o => o.DicPSN == 197 && o.Title == text);
                        if (!dd.Any())
                        {
                            errLs.Add("行号[" + (i + 1) + "]设备分类在字典中不存在,请先添加!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }
                        else
                        {
                            dr[CIdx] = dd.Select(o => o.DicSN).FirstOrDefault();
                        }

                        //设备名称
                        var text2 = dr[TitleIdx].ToString().Trim();
                        if (text2.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + (i + 1) + "]设备名称为空!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }

                        //品牌
                        var text3 = dr[BrandIdx].ToString().Trim();
                        if (text3.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + (i + 1) + "]品牌为空!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }


                        //型号
                        var text4 = dr[SpecIdx].ToString().Trim();
                        if (text4.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + (i + 1) + "]型号为空!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }

                        //设备分类ID
                        var cid     = dataDictionary.Where(o => o.DicPSN == 197 && o.Title == text).Select(o => o.DicSN).FirstOrDefault();
                        var isExist = DevicesRepository.GetQuery(o => o.CategoryId == cid && o.Title == text2 && o.Brand == text3 && o.Spec == text4);
                        if (isExist.Any())
                        {
                            errLs.Add("行号[" + (i + 1) + "]设备记录已经存在!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }

                        #endregion
                    }
                    catch (Exception e)
                    {
                        throw new Exception("创建相关记录失败," + e.Message, e);
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    Devices devices = new Devices();
                    devices.DeviceId  = CommonService.GUID.ToUpper();
                    devices.CreateUID = CurrentUser.UID;
                    devices.CreateDT  = DateTime.Now;

                    sb.Append("insert into ");
                    sb.Append(obj.TableName);
                    sb.Append("(Status,DeviceId,CreateDT,CreateUID,");
                    sb.Append(string.Join(",", fieldCols.Keys));
                    sb.Append(") values(1,'" + devices.DeviceId + "','" + devices.CreateDT + "','" + devices.CreateUID + "',");
                    foreach (var de in fieldCols)
                    {
                        var index = Convert.ToInt32(de.Value) - 65;
                        try
                        {
                            var text = dr[index].ToString().Trim();
                            sb.Append("'" + text + "',");
                        }
                        catch (Exception e)
                        {
                            throw new Exception("列选择超过范围!", e);
                        }
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append(");");
                }
                sb.Append(" commit tran");
                new DBFramework.DBHelper().ExecuteNonQueryText(sb.ToString(), null);
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                LogEngine.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
Exemplo n.º 22
0
        public static OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op = new OpResult();
            var errLs = new List <string>();
            int count = 0, rowno = 0;
            var dt = new DataTable();

            try
            {
                Dictionary <string, char> fieldCols = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var users      = UserInfoService.GetList();
                var barcodeIdx = Convert.ToInt32(fieldCols["Barcode"]) - 65;
                var barcodes   = dt.AsEnumerable().Select(o => o[barcodeIdx].ToString()).Distinct().ToList();
                var payments   = new List <ConsumptionPayment>();
                foreach (var de in fieldCols)
                {
                    var idx = Convert.ToInt32(de.Value) - 65;
                    var col = dt.Columns[idx];
                    if (!dt.Columns.Contains(de.Key))
                    {
                        col.ColumnName = de.Key;
                    }
                }
                dt.Columns.Add("ApiTitle");
                dt.Columns.Add("ValuationType");
                dt.Columns.Add("ProductCode");
                dt.Columns.Add("BuyPrice");
                dt.Columns.Add("StoreId");
                dt.Columns.Add("SalesClassifyId2");
                dt.Columns.Add("CreateUID2");
                dt.Columns.Add("Salesman2");
                dt.Columns.Add("InInventory");
                dt.Columns.Add("Sort", typeof(int));
                object ApiOrderSN = "", ApiTitle = "", ApiCode_11 = 0, ApiCode_12 = 0, ApiCode_20 = 0, ApiCode_21 = 0, ApiCode_19 = 0, PreferentialPrice = 0, Change = 0, WipeZero = 0, TotalAmount = 0, Type = 0;
                int    sort = 1;
                if (!dt.Columns.Contains("ApiOrderSN"))
                {
                    dt.Rows.Clear();
                    errLs.Add("销售流水号位置未指定!");
                }
                else
                {
                    var apiOrderSns = dt.AsEnumerable().Select(o => o["ApiOrderSN"].ToString()).Distinct().Where(o => !o.IsNullOrEmpty()).ToList();
                    payments = ConsumptionPaymentService.FindList(o => apiOrderSns.Contains(o.ApiOrderSN));
                }
                if (!dt.Columns.Contains("SaleDate"))
                {
                    dt.Columns.Add("SaleDate", typeof(DateTime));
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["SaleDate"] = DateTime.Now;
                    }
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var dr = dt.Rows[i];
                    var ApiOrderSNCur = dr.GetValue("ApiOrderSN"); var ChangeCur = dr.GetValue("Change");
                    var ApiCode_11Cur = dr.GetValue("ApiCode_11"); var ApiCode_12Cur = dr.GetValue("ApiCode_12");
                    var ApiCode_20Cur = dr.GetValue("ApiCode_20"); var ApiCode_21Cur = dr.GetValue("ApiCode_21");
                    var ApiCode_19Cur = dr.GetValue("ApiCode_19"); var PreferentialPriceCur = dr.GetValue("PreferentialPrice");
                    var WipeZeroCur = dr.GetValue("WipeZero"); var TotalAmountCur = dr.GetValue("TotalAmount");
                    var TypeCur     = dr.GetValue("Type");
                    var apiTitleCur = "";
                    if (!(ApiCode_11Cur is DBNull))
                    {
                        apiTitleCur += "现金,";
                    }
                    if (!(ApiCode_12Cur is DBNull))
                    {
                        apiTitleCur += "银联,";
                    }
                    if (!(ApiCode_20Cur is DBNull))
                    {
                        apiTitleCur += "支付宝,";
                    }
                    if (!(ApiCode_21Cur is DBNull))
                    {
                        apiTitleCur += "微信,";
                    }
                    if (!(ApiCode_19Cur is DBNull))
                    {
                        apiTitleCur += "即付宝,";
                    }
                    if (dr.GetValue("ApiOrderSN") is DBNull)
                    {
                        dr["ApiOrderSN"] = ApiOrderSN; dr.SetValue("Change", Change);
                        dr.SetValue("ApiCode_11", ApiCode_11); dr.SetValue("ApiCode_12", ApiCode_12);
                        dr.SetValue("ApiCode_20", ApiCode_20); dr.SetValue("ApiCode_21", ApiCode_21);
                        dr.SetValue("ApiCode_19", ApiCode_19); dr.SetValue("PreferentialPrice", PreferentialPrice);
                        dr.SetValue("WipeZero", WipeZero); dr.SetValue("TotalAmount", TotalAmount);
                        dr.SetValue("ApiTitle", ApiTitle); dr.SetValue("Type", Type);
                        sort++;
                    }
                    else
                    {
                        ApiOrderSN     = ApiOrderSNCur; Change = ChangeCur;
                        ApiCode_11     = ApiCode_11Cur; ApiCode_12 = ApiCode_12Cur;
                        ApiCode_20     = ApiCode_20Cur; ApiCode_21 = ApiCode_21Cur;
                        ApiCode_19     = ApiCode_19Cur; PreferentialPrice = PreferentialPriceCur;
                        WipeZero       = WipeZeroCur; TotalAmount = TotalAmountCur;
                        dr["ApiTitle"] = ApiTitle = apiTitleCur.TrimEnd(',');
                        sort           = 1; Type = TypeCur;
                    }
                    //dr["Receive"] = (ApiCode_11Cur is DBNull ? 0 : ApiCode_11Cur.ToType<decimal>()) +
                    //    (ApiCode_12Cur is DBNull ? 0 : ApiCode_12Cur.ToType<decimal>()) +
                    //    (ApiCode_20Cur is DBNull ? 0 : ApiCode_20Cur.ToType<decimal>()) +
                    //    (ApiCode_21Cur is DBNull ? 0 : ApiCode_21Cur.ToType<decimal>()) +
                    //    (ApiCode_19Cur is DBNull ? 0 : ApiCode_19Cur.ToType<decimal>()) -
                    //    (ChangeCur is DBNull ? 0 : ChangeCur.ToType<decimal>());

                    dr["StoreId"]     = System.Web.HttpContext.Current.Request["storeId"];
                    dr["InInventory"] = System.Web.HttpContext.Current.Request["InInventory"];
                    dr["Sort"]        = sort;
                }

                var removeDrs = new List <DataRow>();
                var apisns    = dt.AsEnumerable().GroupBy(o => o["ApiOrderSN"].ToString()).Select(o => o.Key).ToList();
                var products  = ProductService.GetProductsBybars(barcodes);
                count = apisns.Count;
                rowno = obj.MinRow;
                for (int i = 0; i < apisns.Count; i++)
                {
                    var apiSn = apisns[i];
                    var drs   = dt.Select("ApiOrderSN='" + apiSn + "'");
                    if (payments.Any(o => o.ApiOrderSN == apiSn))
                    {
                        errLs.Add("行号[" + rowno + "]&nbsp;流水号[" + apiSn + "]已存在!");
                        removeDrs.AddRange(drs);
                        rowno += drs.Length;
                        continue;
                    }
                    var     receive     = drs.Max(o => o.GetValue("Receive").ToType <decimal>());
                    int     j           = 0;
                    decimal totalAmount = 0;
                    bool    haszs       = false;
                    foreach (DataRow dr in drs)
                    {
                        var text = dr["Barcode"].ToString();
                        if (text.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + (rowno + j) + "]条码不存在!");
                            removeDrs.AddRange(drs);
                            break;
                        }
                        //var pro = products.FirstOrDefault(o => o.Barcode == text || ("," + o.Barcodes + ",").Contains("," + text + ","));
                        var pro = products.Select(string.Format("Barcode='{0}' or ','+Barcodes+',' like '%,{0},%'", text));
                        if (pro.Length <= 0)
                        {
                            errLs.Add("行号[" + (rowno + j) + "]&nbsp;流水号[" + apiSn + "]&nbsp;条码[" + text + "]档案不存在!");
                            removeDrs.AddRange(drs);
                            break;
                        }
                        dr["ProductCode"]   = pro[0]["ProductCode"];
                        dr["BuyPrice"]      = pro[0]["BuyPrice"];
                        dr["ValuationType"] = pro[0]["ValuationType"];
                        text = dr.GetValue("Type").ToString();
                        dr.SetValue("Type", text == "换货" ? "1" : text == "退货" ? "2" : text == "退单" ? "3" : "0");
                        text = dr.GetValue("CreateUID").ToString();
                        if (!text.IsNullOrEmpty() && users.Any(o => o.FullName == text || o.UserCode == text))
                        {
                            var user = users.FirstOrDefault(o => o.FullName == text || o.UserCode == text);
                            dr["CreateUID2"] = user == null ? "" : user.UID;
                            if (user == null)
                            {
                                dr["CreateUID"] = "";
                            }
                        }
                        else
                        {
                            errLs.Add("行号[" + (rowno + j) + "]&nbsp;流水号[" + apiSn + "]&nbsp;收银员" + (text.IsNullOrEmpty() ? "为空" : "[" + text + "]档案不存在!"));
                            removeDrs.AddRange(drs);
                            break;
                        }
                        text = dr.GetValue("Salesman").ToString();
                        if (!text.IsNullOrEmpty() && users.Any(o => o.FullName == text || o.UserCode == text))
                        {
                            var user = users.FirstOrDefault(o => o.FullName == text || o.UserCode == text);
                            dr["Salesman2"] = user == null ? "" : user.UID;
                            if (user == null)
                            {
                                dr["Salesman"] = "";
                            }
                        }
                        else
                        {
                            errLs.Add("行号[" + (rowno + j) + "]&nbsp;流水号[" + apiSn + "]&nbsp;导购员" + (text.IsNullOrEmpty() ? "为空" : "[" + text + "]档案不存在!"));
                            removeDrs.AddRange(drs);
                            break;
                        }
                        text = dr.GetValue("SalesClassifyId").ToString();
                        dr["SalesClassifyId2"] = text == "赠送" ? "49" : "47";
                        if (text == "赠送")
                        {
                            dr.SetValue("SubTotal", 0);
                            dr.SetValue("ActualPrice", 0);
                            if (receive == 0)
                            {
                                dr.SetValue("TotalAmount", 0);
                            }
                            haszs = true;
                        }
                        totalAmount += dr.GetValue("ActualPrice").ToType <decimal>() * dr.GetValue("PurchaseNumber").ToType <decimal>();
                        j++;
                    }
                    if (receive > 0 && haszs)
                    {
                        drs.Each(dr =>
                        {
                            dr.SetValue("TotalAmount", totalAmount);//重算应付金额
                        });
                    }
                    rowno += drs.Length;
                }
                foreach (var dr in removeDrs)
                {
                    try { dt.Rows.Remove(dr); }
                    catch { }
                }
                saleOrderCache.Set(CacheKey, dt);
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
Exemplo n.º 23
0
 public static System.Collections.Generic.Dictionary <string, object> UploadImages(System.Web.HttpFileCollectionBase HttpFileCollectionBase, string DataSource)
 {
     return(UploadImages(HttpFileCollectionBase, DataSource, true, 5));
 }
Exemplo n.º 24
0
        public OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }
                var categorys       = ProductCategoryService.GetList();
                var otherClass      = categorys.FirstOrDefault(o => o.Title.StartsWith("其"));
                var brands          = BrandService.GetList();
                var otherBrand      = brands.FirstOrDefault(o => o.Title.StartsWith("其"));
                var brandClass      = DictionaryService.GetChildList(5);
                var otherBrandClass = brandClass.FirstOrDefault(o => o.Title.StartsWith("其"));//?
                var units           = DictionaryService.GetSubUnitCategories();
                var otherUnit       = units.FirstOrDefault(o => o.Title.StartsWith("其"));
                var products        = GetList();
                var maxCate         = ProductCategoryService.MaxSN() + 1;
                var maxBrand        = BrandService.MaxSN() + 1;
                var maxDict         = DictionaryService.MaxSN() + 1;

                var clsIdx   = Convert.ToInt32(fieldCols["CategorySN"]) - 65;
                var brandIdx = Convert.ToInt32(fieldCols["BrandSN"]) - 65;
                var unitIdx  = Convert.ToInt32(fieldCols["SubUnitId"]) - 65;
                var titleIdx = Convert.ToInt32(fieldCols["Barcode"]) - 65;
                count = dt.Rows.Count;
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        var dr = dt.Rows[i];
                        #region 条码验证
                        var text = dr[titleIdx].ToString();
                        if (text.IsNullOrEmpty())
                        {
                            errLs.Add("行号[" + i + "]条码为空!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }
                        else if (products.Any(o => o.Barcode == text))
                        {
                            errLs.Add("条码[" + text + "]已存在!");
                            dt.Rows.RemoveAt(i);
                            continue;
                        }
                        else
                        {
                            products.Add(new ProductRecord()
                            {
                                Barcode = text
                            });
                        }
                        #endregion
                        #region 处理类别
                        text = dr[clsIdx].ToString();
                        if (!text.IsNullOrEmpty() && text.Contains("/"))
                        {
                            var cates  = text.Split('/');
                            var first  = cates.FirstOrDefault();
                            var third  = cates.LastOrDefault();
                            var second = "";
                            if (cates.Length == 3)
                            {
                                second = cates[1];
                                third  = cates[2];
                            }
                            else if (cates.Length == 2)
                            {
                                second = cates[1];
                                third  = null;
                            }
                            else if (cates.Length > 3)
                            {
                                second = cates[1];
                                third  = text.Replace(first + "/" + second + "/", "");
                            }
                            var parent = categorys.FirstOrDefault(o => o.Title == first);

                            var cls = parent != null?categorys.FirstOrDefault(o => o.CategoryPSN == parent.CategorySN && o.Title == second) : null;

                            cls = cls != null && !third.IsNullOrEmpty() ? categorys.FirstOrDefault(o => o.CategoryPSN == cls.CategorySN && o.Title == third) : cls;
                            if (cls != null)
                            {
                                dr[clsIdx] = cls.CategorySN.ToString();
                            }
                            else
                            {
                                if (obj.RefCreate)
                                {
                                    var list = new List <ProductCategory>();
                                    cls = categorys.FirstOrDefault(o => o.Title == first);
                                    int   psn   = 0;
                                    short grade = 2;
                                    if (cls == null)
                                    {
                                        parent = new ProductCategory()
                                        {
                                            CategorySN   = maxCate,
                                            Title        = first,
                                            CategoryCode = 1,
                                            Grade        = 1,
                                            State        = 1,
                                        };
                                        list.Add(parent);
                                        psn = parent.CategorySN;
                                        var child = new ProductCategory()
                                        {
                                            CategoryPSN  = psn,
                                            CategorySN   = ++maxCate,
                                            Title        = second,
                                            CategoryCode = 1,
                                            Grade        = grade,
                                            State        = 1,
                                        };
                                        list.Add(child);
                                        psn   = child.CategorySN;
                                        grade = 3;
                                        if (!third.IsNullOrEmpty())
                                        {
                                            child = new ProductCategory()
                                            {
                                                CategoryPSN  = psn,
                                                CategorySN   = ++maxCate,
                                                Title        = third,
                                                CategoryCode = 1,
                                                Grade        = grade,
                                                State        = 1,
                                            };
                                            psn = child.CategorySN;
                                            list.Add(child);
                                        }
                                    }
                                    else
                                    {
                                        psn = cls.CategorySN;
                                        cls = categorys.FirstOrDefault(o => o.Title == second);
                                        if (cls == null)
                                        {
                                            var maxcode = ProductCategoryService.MaxCode(psn);
                                            var child   = new ProductCategory()
                                            {
                                                CategoryPSN  = psn,
                                                CategorySN   = ++maxCate,
                                                Title        = second,
                                                CategoryCode = ++maxcode,
                                                Grade        = grade,
                                                State        = 1
                                            };
                                            list.Add(child);
                                            psn   = child.CategorySN;
                                            grade = 3;
                                        }
                                        else
                                        {
                                            psn = cls.CategorySN;
                                        }
                                        if (!third.IsNullOrEmpty())
                                        {
                                            cls = categorys.FirstOrDefault(o => o.Title == third);
                                            if (cls == null)
                                            {
                                                var maxcode = ProductCategoryService.MaxCode(psn);
                                                var child   = new ProductCategory()
                                                {
                                                    CategoryPSN  = psn,
                                                    CategorySN   = ++maxCate,
                                                    Title        = third,
                                                    CategoryCode = ++maxcode,
                                                    Grade        = grade,
                                                    State        = 1
                                                };
                                                list.Add(child);
                                                psn = child.CategorySN;
                                            }
                                            else
                                            {
                                                psn = cls.CategorySN;
                                            }
                                        }
                                    }
                                    ProductCategoryService.AddRange(list);
                                    categorys.AddRange(list);
                                    dr[clsIdx] = psn.ToString();
                                }
                                else if (otherClass != null)
                                {
                                    dr[clsIdx] = otherClass.CategorySN.ToString();
                                }
                                else
                                {
                                    errLs.Add("条码[" + dr[titleIdx] + "]类别不存在!");
                                    dt.Rows.RemoveAt(i);//去除不导入
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            errLs.Add("条码[" + dr[titleIdx] + "]类别不存在!");
                            dt.Rows.RemoveAt(i);//去除不导入
                            continue;
                        }
                        #endregion
                        #region 处理品牌
                        text = dr[brandIdx].ToString();
                        if (!text.IsNullOrEmpty())
                        {
                            var cls = brands.FirstOrDefault(o => o.Title == text);
                            if (cls != null)
                            {
                                dr[brandIdx] = cls.BrandSN.ToString();
                            }
                            else
                            {
                                if (obj.RefCreate)
                                {
                                    if (otherBrandClass == null)
                                    {
                                        errLs.Add("条码[" + dr[titleIdx] + "]品牌分类不存在!");
                                        dt.Rows.RemoveAt(i);
                                        continue;
                                    }
                                    var data = new ProductBrand()
                                    {
                                        //BrandSN = maxBrand++,
                                        Title      = text,
                                        ClassifyId = otherBrandClass.DicSN,
                                        JianPin    = "",
                                        State      = 1
                                    };
                                    BrandService.SaveOrUpdate(data);
                                    brands.Add(data);
                                    dr[brandIdx] = data.BrandSN.ToString();
                                }
                                else if (otherBrand != null)
                                {
                                    dr[brandIdx] = otherBrand.BrandSN.ToString();
                                }
                                else
                                {
                                    errLs.Add("条码[" + dr[titleIdx] + "]品牌不存在!");
                                    dt.Rows.RemoveAt(i);
                                    continue;
                                }
                            }
                        }
                        #endregion
                        #region 处理单位
                        text = dr[unitIdx].ToString();
                        if (!text.IsNullOrEmpty())
                        {
                            var cls = units.FirstOrDefault(o => o.Title == text);
                            if (cls != null)
                            {
                                dr[unitIdx] = cls.DicSN.ToString();
                            }
                            else
                            {
                                if (obj.RefCreate)
                                {
                                    var data = new SysDataDictionary()
                                    {
                                        DicPSN = 4,
                                        //DicSN = maxDict++,
                                        Status = true,
                                        Title  = text,
                                    };
                                    DictionaryService.SaveOrUpdate(data);
                                    units.Add(data);
                                    dr[unitIdx] = data.DicSN.ToString();
                                }
                                else if (otherUnit != null)
                                {
                                    dr[unitIdx] = otherUnit.DicSN.ToString();
                                }
                                else
                                {
                                    errLs.Add("条码[" + dr[titleIdx] + "]单位不存在!");
                                    dt.Rows.RemoveAt(i);
                                    continue;
                                }
                            }
                        }
                        #endregion
                    }
                    catch (Exception e)
                    {
                        throw new Exception("创建相关记录失败," + e.Message, e);
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("insert into ");
                    sb.Append(obj.TableName);
                    sb.Append("(State,");
                    sb.Append(string.Join(",", fieldCols.Keys));
                    sb.Append(") values(1,");
                    foreach (var de in fieldCols)
                    {
                        var index = Convert.ToInt32(de.Value) - 65;
                        try
                        {
                            var text = dr[index].ToString().Trim();
                            sb.Append("'" + text + "',");
                        }
                        catch (Exception e)
                        {
                            throw new Exception("列选择超过范围!", e);
                        }
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                    sb.Append(");");
                }
                sb.Append(" commit tran");
                if (dt.Rows.Count > 0)
                {
                    new DBFramework.DBHelper().ExecuteNonQueryText(sb.ToString(), null);
                }
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                LogEngine.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }
        public JsonResult UpFileData()
        {
            return(ExecuteFunctionRun(() =>
            {
                ActionResult result = new ActionResult(true, "");
                string strNewAttachIds = string.Empty;
                string dataField = Request.Form["dataField"];
                string instanceID = Request.Form["InstanceID"] + string.Empty;
                //新加的属性,待确认
                //ERROR:
                string schemaCode = Request.Form["SchemaCode"] + string.Empty;
                string bizObjectID = Request.Form["BizObjectID"] + string.Empty;
                //string workflowPackage = Request.Form["WorkflowPackage"] + string.Empty;
                //string workflowName = Request.Form["WorkflowName"] + string.Empty;
                if (dataField == string.Empty)
                {
                    result.Success = false;
                    result.Message = "数据项名称为空";
                    return Json(result);
                }
                System.Web.HttpPostedFileBase theFile;
                //说明:若控件的参数 <PARAM NAME="DelFileField" VALUE="DELETE_FILE_NAMES">
                //则,从Request.Form得到的DELETE_FILE_NAMES集合包含了所有需要删除的文件
                //也就是客户端修改过的文件名
                string[] delFileNames = Request.Form.GetValues("DELETE_FILE_NAMES");
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;

                try
                {
                    OThinker.H3.Data.AttachmentHeader[] headers = null;
                    if (instanceID != string.Empty)
                    {
                        headers = AppUtility.Engine.BizObjectManager.QueryAttachment(schemaCode, bizObjectID, dataField, OThinker.Data.BoolMatchValue.True, string.Empty);
                    }

                    // 增加保存附件文件
                    for (int i = 0; i < uploadFiles.Count; i++)
                    {
                        theFile = uploadFiles[i];
                        // "EDITFILE"和客户端的BeginSaveToURL的第二个参数一致
                        if (uploadFiles.GetKey(i).ToUpper() == "EDITFILE")
                        {
                            // 写入FILE数据
                            string fname = theFile.FileName;
                            int fsize = theFile.ContentLength;
                            string contentType = theFile.ContentType;
                            byte[] buffer = new byte[theFile.ContentLength];
                            theFile.InputStream.Read(buffer, 0, fsize);

                            OThinker.H3.Data.Attachment attachment = new OThinker.H3.Data.Attachment()
                            {
                                ObjectID = Guid.NewGuid().ToString(),
                                FileName = fname,
                                ContentType = string.Empty,
                                Content = buffer,
                                DataField = Server.UrlDecode(dataField),
                                CreatedBy = this.UserValidator.UserID,
                                Downloadable = true,
                                BizObjectId = bizObjectID,
                                BizObjectSchemaCode = schemaCode
                            };

                            strNewAttachIds += attachment.ObjectID + ",";

                            this.Engine.BizObjectManager.AddAttachment(attachment);
                        }
                    }
                    if (headers != null && delFileNames != null)
                    {
                        foreach (OThinker.H3.Data.AttachmentHeader header in headers)
                        {
                            if (Array.IndexOf <string>(delFileNames, header.FileName) > -1)
                            {
                                this.Engine.BizObjectManager.RemoveAttachment(this.UserValidator.UserID,
                                                                              schemaCode,
                                                                              header.BizObjectId,
                                                                              header.ObjectID);
                            }
                        }
                    }
                    // Response.Write(strNewAttachIds);
                    result.Message = strNewAttachIds;
                    return Json(result);
                }
                catch (Exception err)
                {
                    result.Success = false;
                    result.Message = "NTKO Attachment ERROR:" + err.ToString();
                    AppUtility.Engine.LogWriter.Write("NTKO Attachment ERROR:" + err.ToString());
                    return Json(result);
                }
            }));
        }
Exemplo n.º 26
0
        public OpResult ImportSet(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName, ref Dictionary <string, char> fieldCols, ref System.Data.DataTable dt)
        {
            var op = new OpResult();

            if (httpFiles.Count <= 0 || httpFiles[0].ContentLength <= 0)
            {
                op.Message = "请先选择Excel文件";
                return(op);
            }
            var stream = httpFiles[0].InputStream;
            var ext    = httpFiles[0].FileName.Substring(httpFiles[0].FileName.LastIndexOf("."));

            if (!(ext.Equals(".xls", StringComparison.CurrentCultureIgnoreCase) ||
                  ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)))
            {
                op.Message = "请先选择Excel文件";
                return(op);
            }
            fieldCols = fieldCols ?? new Dictionary <string, char>();
            if (!fieldName.IsNullOrEmpty() && !columnName.IsNullOrEmpty())
            {
                var fields  = fieldName.Split(',');
                var columns = columnName.Split(',');
                if (fields.Length != columns.Length)
                {
                    op.Message = "配置的字段和列数不一致!";
                    return(op);
                }
                for (var i = 0; i < fields.Length; i++)
                {
                    if (columns[i].IsNullOrEmpty())
                    {
                        continue;
                    }
                    fieldCols[fields[i]] = Convert.ToChar(columns[i]);
                }
                obj.FieldJson = fieldCols.Select(o => new { o.Key, o.Value }).ToJson();
            }
            if (obj.Id == 0)
            {
                if (!ImportSetRepository.GetQuery(o => o.TableName == obj.TableName).Any())
                {
                    ImportSetRepository.Add(obj);
                }
            }
            else
            {
                var res = ImportSetRepository.Get(obj.Id);
                obj.ToCopyProperty(res);
            }
            ImportSetRepository.SaveChanges();

            dt = new ExportExcel().ToDataTable(stream, minRow: obj.MinRow, maxRow: obj.MaxRow.HasValue ? obj.MaxRow.Value : Int32.MaxValue);
            if (dt == null || dt.Rows.Count <= 0)
            {
                op.Message   = "无数据,无法导入!";
                op.Successed = false;
                return(op);
            }

            #region 允许配置在同一列
            var cols = fieldCols.GroupBy(o => o.Value).Where(o => o.Count() > 1).ToList();//取重复列
            foreach (var item in cols)
            {
                System.Diagnostics.Debug.WriteLine(item.Key);//重复列value
                var idx = Convert.ToInt32(item.Key) - 65;
                foreach (var subitem in item)
                {
                    System.Diagnostics.Debug.WriteLine(subitem.Key);//重复列key
                    var lastValue = Convert.ToChar(fieldCols.Values.OrderBy(o => o).LastOrDefault() + 1);
                    if (dt.Columns[idx].CloneTo(subitem.Key))
                    {
                        fieldCols[subitem.Key] = lastValue;
                    }
                }
            }
            #endregion

            op.Successed = true;
            return(op);
        }
Exemplo n.º 27
0
        public static OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName)
        {
            var op    = new OpResult();
            var errLs = new List <string>();
            int count = 0;

            try
            {
                //防伪码在同商户下唯一,防止重复
                SecurityCodes = BaseService <MembershipCard> .CurrentRepository.Entities.Where(o => o.CompanyId == CommonService.CompanyId).Select(o => o.SecurityCode).ToList();

                Dictionary <string, char> fieldCols = null;
                DataTable dt = null;
                op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt);
                if (!op.Successed)
                {
                    return(op);
                }

                var cardsnIdx  = fieldCols.GetValue("CardSN").ToType <int>() - 65;
                var balanceIdx = fieldCols.GetValue("Balance").ToType <int>() - 65;
                var nameIdx    = fieldCols.GetValue("MemberId").ToType <int>() - 65;
                var mobileIdx  = fieldCols.GetValue("MobilePhone").ToType <int>() - 65;
                count = dt.Rows.Count;
                if (cardsnIdx < 0 || balanceIdx < 0)
                {
                    errLs.Add("卡号或余额列不能为空!");
                    dt.Rows.Clear();
                    count = errLs.Count;
                }
                var cardsns = new List <string>();
                var names   = new List <string>();
                var mobiles = new List <string>();
                foreach (DataRow dr in dt.Rows)
                {
                    var cardsn = dr.GetValue(cardsnIdx).ToString();
                    var name   = dr.GetValue(nameIdx).ToString();
                    var mobile = dr.GetValue(mobileIdx).ToString();
                    if (!cardsn.IsNullOrEmpty() && !cardsns.Contains(cardsn))
                    {
                        cardsns.Add(cardsn);
                    }
                    if (!name.IsNullOrEmpty() && !names.Contains(name))
                    {
                        names.Add(name);
                    }
                    if (!mobile.IsNullOrEmpty() && !mobiles.Contains(mobile))
                    {
                        mobiles.Add(mobile);
                    }
                }

                var cards   = new List <MembershipCard>();
                var members = new List <Members>();
                if (cardsns.Any())
                {
                    cards = CurrentRepository.QueryEntity.Where(o => o.CompanyId == CommonService.CompanyId && cardsns.Contains(o.CardSN)).ToList();
                }
                if (names.Any() || mobiles.Any())
                {
                    members = MembersService.FindList(o => names.Contains(o.RealName) || mobiles.Contains(o.MobilePhone));
                }

                var storeId = System.Web.HttpContext.Current.Request["StoreId"];
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    var     dr   = dt.Rows[i];
                    var     text = dr.GetValue(cardsnIdx).ToString().Trim();
                    decimal val  = 0;
                    if (text.IsNullOrEmpty())
                    {
                        dt.Rows.RemoveAt(i);//去除不导入
                        continue;
                    }
                    else if (!decimal.TryParse(text, out val))
                    {
                        errLs.Add("卡号[" + text + "]不合法!");
                        dt.Rows.RemoveAt(i);//去除不导入
                        continue;
                    }
                    else if (cards.Any(o => o.CardSN == text) && System.Web.HttpContext.Current.Request["updateBalance"] != "on")
                    {
                        errLs.Add("卡号[" + text + "]已存在!");
                        dt.Rows.RemoveAt(i);//去除不导入
                        continue;
                    }
                    else
                    {
                        cards.Add(new MembershipCard()
                        {
                            CardSN = text
                        });
                    }
                    var name   = dr.GetValue(nameIdx).ToString();
                    var mobile = dr.GetValue(mobileIdx).ToString();
                    if (!(name.IsNullOrEmpty() || mobile.IsNullOrEmpty()))
                    {
                        var mem = members.FirstOrDefault(o => o.RealName == name && o.MobilePhone == mobile);
                        if (mem != null)
                        {
                            dr[nameIdx] = mem.MemberId;
                        }
                        else
                        {
                            if (obj.RefCreate)
                            {
                                mem = new Members()
                                {
                                    CreateDT    = DateTime.Now,
                                    CreateUID   = CurrentUser.UID,
                                    RealName    = name,
                                    MobilePhone = mobile,
                                    Sex         = -1,
                                    Status      = 1,
                                    StoreId     = storeId.IsNullOrEmpty() ? "00" : storeId,
                                    CompanyId   = obj.CompanyId,
                                    MemberNo    = CommonRules.MemberNum("00"),
                                    MemberId    = CommonRules.GUID
                                };
                                MembersService.Add(mem);
                                dr[nameIdx] = mem.MemberId;
                            }
                        }
                    }
                }
                fieldCols.Remove("MobilePhone");
                var cardTypeId = System.Web.HttpContext.Current.Request["CardTypeId"];
                var prefix     = DateTime.Now.ToString("yyMMdd");
                var maxsn      = CurrentRepository.QueryEntity.Where(o => o.CompanyId == obj.CompanyId && o.BatchSN.StartsWith(prefix)).Select(o => o.BatchSN).Max();
                int sn         = 1;
                if (!maxsn.IsNullOrEmpty())
                {
                    sn = int.Parse(maxsn.Substring(maxsn.Length - 2, 2)) + 1;
                    if (sn >= 100)
                    {
                        errLs.Add("当天制卡批次号已使用完!");
                        dt.Rows.Clear();
                    }
                }
                prefix = prefix + sn.ToString("00");
                StringBuilder sb = new StringBuilder();
                sb.Append("begin tran ");
                foreach (DataRow dr in dt.Rows)
                {
                    //判断卡号是否操作
                    var cardSn = dr.GetValue(cardsnIdx).ToString().Trim();
                    //var isExit = CurrentRepository.Entities.Any(o => o.CompanyId == CommonService.CompanyId && o.CardSN == cardSn);
                    //判断是否只做更新动作 重复的卡号做余额更新动作
                    if (cards.Any(o => o.CardSN == cardSn) && System.Web.HttpContext.Current.Request["updateBalance"] == "on")
                    {
                        sb.Append("UPDATE " + obj.TableName);
                        sb.Append(" SET ");
                        sb.Append("Balance= ");
                        sb.Append(dr.GetValue(balanceIdx).ToString().Trim());
                        sb.Append(" WHERE ");
                        sb.Append(" CardSN= ");
                        sb.Append("'" + cardSn + "'");
                        sb.Append(" AND ");
                        sb.Append(" CompanyId= ");
                        sb.Append(CommonService.CompanyId);
                        sb.Append(";");
                    }
                    else
                    {
                        sb.Append("insert into ");
                        sb.Append(obj.TableName);
                        sb.Append("(CompanyId,BatchSN,CardTypeId,State,CreateUID,SecurityCode,");
                        sb.Append(string.Join(",", fieldCols.Keys));
                        sb.Append(") values(");
                        sb.AppendFormat("{0},", obj.CompanyId);
                        sb.AppendFormat("'{0}',", prefix);
                        sb.AppendFormat("'{0}',", cardTypeId);
                        sb.AppendFormat("1,");
                        sb.AppendFormat("'{0}',", CurrentUser.UID);
                        sb.AppendFormat("'{0}',", GetSecurityCode);
                        foreach (var de in fieldCols)
                        {
                            var index = Convert.ToInt32(de.Value) - 65;
                            try
                            {
                                var text = dr[index].ToString();
                                sb.Append("'" + text + "',");
                            }
                            catch (Exception e)
                            {
                                throw new Exception("列选择超过范围!", e);
                            }
                        }
                        sb = sb.Remove(sb.Length - 1, 1);
                        sb.Append(");");
                    }
                    sn++;
                }
                if (dt.Rows.Count > 0)
                {
                    sb.Append("insert into ");
                    sb.Append("MakingMembershipCard");
                    sb.Append("(CompanyId,BatchSN,CardTypeId,State,CreateUID,MakeNumber");
                    sb.Append(") values(");
                    sb.AppendFormat("{0},'{1}','{2}',{3},'{4}','{5}')", obj.CompanyId, prefix, cardTypeId, 1, CurrentUser.UID, dt.Rows.Count);

                    sb.Append(" commit tran");
                    op.Successed = new Pharos.Logic.DAL.CommonDAL()._db.ExecuteNonQueryText(sb.ToString(), null) > 0;
                    if (op.Successed)
                    {
                        Log.WriteInsert("会员卡导入", Sys.LogModule.会员管理);
                    }
                    ("会员卡导入:" + sb.ToString()).ToLog();
                }
            }
            catch (Exception ex)
            {
                op.Message   = ex.Message;
                op.Successed = false;
                Log.WriteError(ex);
                errLs.Add("导入出现异常!");
            }
            return(CommonService.GenerateImportHtml(errLs, count));
        }