Esempio n. 1
0
        // Returns true if hit an enemy entity
        public bool WeaponDamage(DaggerfallUnityItem strikingWeapon, bool arrowHit, Transform hitTransform, Vector3 impactPosition, Vector3 direction)
        {
            DaggerfallEntityBehaviour entityBehaviour  = hitTransform.GetComponent <DaggerfallEntityBehaviour>();
            DaggerfallMobileUnit      entityMobileUnit = hitTransform.GetComponentInChildren <DaggerfallMobileUnit>();
            EnemyMotor  enemyMotor  = hitTransform.GetComponent <EnemyMotor>();
            EnemySounds enemySounds = hitTransform.GetComponent <EnemySounds>();

            // Check if hit a mobile NPC
            MobilePersonNPC mobileNpc = hitTransform.GetComponent <MobilePersonNPC>();

            if (mobileNpc)
            {
                if (!mobileNpc.IsGuard)
                {
                    EnemyBlood blood = hitTransform.GetComponent <EnemyBlood>();
                    if (blood)
                    {
                        blood.ShowBloodSplash(0, impactPosition);
                    }
                    mobileNpc.Motor.gameObject.SetActive(false);
                    playerEntity.TallyCrimeGuildRequirements(false, 5);
                    playerEntity.CrimeCommitted = PlayerEntity.Crimes.Murder;
                    playerEntity.SpawnCityGuards(true);

                    // Allow custom race handling of weapon hit against mobile NPCs, e.g. vampire feeding or lycanthrope killing
                    if (entityBehaviour)
                    {
                        entityBehaviour.Entity.SetHealth(0);
                        RacialOverrideEffect racialOverride = GameManager.Instance.PlayerEffectManager.GetRacialOverrideEffect();
                        if (racialOverride != null)
                        {
                            racialOverride.OnWeaponHitEntity(GameManager.Instance.PlayerEntity, entityBehaviour.Entity);
                        }
                    }
                }
                else
                {
                    playerEntity.CrimeCommitted = PlayerEntity.Crimes.Assault;
                    GameObject guard = playerEntity.SpawnCityGuard(mobileNpc.transform.position, mobileNpc.transform.forward);
                    entityBehaviour  = guard.GetComponent <DaggerfallEntityBehaviour>();
                    entityMobileUnit = guard.GetComponentInChildren <DaggerfallMobileUnit>();
                    enemyMotor       = guard.GetComponent <EnemyMotor>();
                    enemySounds      = guard.GetComponent <EnemySounds>();
                }
                mobileNpc.Motor.gameObject.SetActive(false);
            }

            // Check if hit an entity and remove health
            if (entityBehaviour)
            {
                if (entityBehaviour.EntityType == EntityTypes.EnemyMonster || entityBehaviour.EntityType == EntityTypes.EnemyClass)
                {
                    EnemyEntity enemyEntity = entityBehaviour.Entity as EnemyEntity;

                    // Calculate damage
                    int  animTime = (int)(ScreenWeapon.GetAnimTime() * 1000);   // Get animation time, converted to ms.
                    bool isEnemyFacingAwayFromPlayer = entityMobileUnit.Summary.AnimStateRecord % 5 > 2 &&
                                                       entityMobileUnit.Summary.EnemyState != MobileStates.SeducerTransform1 &&
                                                       entityMobileUnit.Summary.EnemyState != MobileStates.SeducerTransform2;
                    int damage = FormulaHelper.CalculateAttackDamage(playerEntity, enemyEntity, isEnemyFacingAwayFromPlayer, animTime, strikingWeapon);

                    // Break any "normal power" concealment effects on player
                    if (playerEntity.IsMagicallyConcealedNormalPower && damage > 0)
                    {
                        EntityEffectManager.BreakNormalPowerConcealmentEffects(GameManager.Instance.PlayerEntityBehaviour);
                    }

                    // Play arrow sound and add arrow to target's inventory
                    if (arrowHit)
                    {
                        DaggerfallUnityItem arrow = ItemBuilder.CreateItem(ItemGroups.Weapons, (int)Weapons.Arrow);
                        enemyEntity.Items.AddItem(arrow);
                    }

                    // Play hit sound and trigger blood splash at hit point
                    if (damage > 0)
                    {
                        if (usingRightHand)
                        {
                            enemySounds.PlayHitSound(currentRightHandWeapon);
                        }
                        else
                        {
                            enemySounds.PlayHitSound(currentLeftHandWeapon);
                        }

                        EnemyBlood blood = hitTransform.GetComponent <EnemyBlood>();
                        if (blood)
                        {
                            blood.ShowBloodSplash(enemyEntity.MobileEnemy.BloodIndex, impactPosition);
                        }

                        // Knock back enemy based on damage and enemy weight
                        if (enemyMotor)
                        {
                            if (enemyMotor.KnockbackSpeed <= (5 / (PlayerSpeedChanger.classicToUnitySpeedUnitRatio / 10)) &&
                                entityBehaviour.EntityType == EntityTypes.EnemyClass ||
                                enemyEntity.MobileEnemy.Weight > 0)
                            {
                                float enemyWeight    = enemyEntity.GetWeightInClassicUnits();
                                float tenTimesDamage = damage * 10;
                                float twoTimesDamage = damage * 2;

                                float knockBackAmount = ((tenTimesDamage - enemyWeight) * 256) / (enemyWeight + tenTimesDamage) * twoTimesDamage;
                                float KnockbackSpeed  = (tenTimesDamage / enemyWeight) * (twoTimesDamage - (knockBackAmount / 256));
                                KnockbackSpeed /= (PlayerSpeedChanger.classicToUnitySpeedUnitRatio / 10);

                                if (KnockbackSpeed < (15 / (PlayerSpeedChanger.classicToUnitySpeedUnitRatio / 10)))
                                {
                                    KnockbackSpeed = (15 / (PlayerSpeedChanger.classicToUnitySpeedUnitRatio / 10));
                                }
                                enemyMotor.KnockbackSpeed     = KnockbackSpeed;
                                enemyMotor.KnockbackDirection = direction;
                            }
                        }

                        if (DaggerfallUnity.Settings.CombatVoices && entityBehaviour.EntityType == EntityTypes.EnemyClass && Dice100.SuccessRoll(40))
                        {
                            Genders gender;
                            if (entityMobileUnit.Summary.Enemy.Gender == MobileGender.Male || enemyEntity.MobileEnemy.ID == (int)MobileTypes.Knight_CityWatch)
                            {
                                gender = Genders.Male;
                            }
                            else
                            {
                                gender = Genders.Female;
                            }

                            bool heavyDamage = damage >= enemyEntity.MaxHealth / 4;
                            enemySounds.PlayCombatVoice(gender, false, heavyDamage);
                        }
                    }
                    else
                    {
                        if ((!arrowHit && !enemyEntity.MobileEnemy.ParrySounds) || strikingWeapon == null)
                        {
                            ScreenWeapon.PlaySwingSound();
                        }
                        else if (enemyEntity.MobileEnemy.ParrySounds)
                        {
                            enemySounds.PlayParrySound();
                        }
                    }

                    // Handle weapon striking enchantments - this could change damage amount
                    if (strikingWeapon != null && strikingWeapon.IsEnchanted)
                    {
                        EntityEffectManager effectManager = GetComponent <EntityEffectManager>();
                        if (effectManager)
                        {
                            damage = effectManager.DoItemEnchantmentPayloads(EnchantmentPayloadFlags.Strikes, strikingWeapon, GameManager.Instance.PlayerEntity.Items, enemyEntity.EntityBehaviour, damage);
                        }
                        strikingWeapon.RaiseOnWeaponStrikeEvent(entityBehaviour, damage);
                    }

                    // Remove health
                    enemyEntity.DecreaseHealth(damage);

                    // Handle attack from player
                    enemyEntity.EntityBehaviour.HandleAttackFromSource(GameManager.Instance.PlayerEntityBehaviour);

                    // Allow custom race handling of weapon hit against enemies, e.g. vampire feeding or lycanthrope killing
                    RacialOverrideEffect racialOverride = GameManager.Instance.PlayerEffectManager.GetRacialOverrideEffect();
                    if (racialOverride != null)
                    {
                        racialOverride.OnWeaponHitEntity(GameManager.Instance.PlayerEntity, entityBehaviour.Entity);
                    }

                    return(true);
                }
            }

            return(false);
        }
        public void CreateNewReport(string isReset, int belongYear, int belongMonth)
        {
            if (isReset == "T")
            {
                this.ComprehensiveDbContext.Set <R_G_GoodsReport>().Delete(d => d.BelongYear == belongYear && d.BelongMonth == belongMonth);
            }

            var deptOrgList   = EnumBaseHelper.GetEnumDef("System.DeptOrg").EnumItem.ToList();
            var goodsInfoList = this.ComprehensiveDbContext.Set <S_G_GoodsInfo>().ToList();
            int lastYear      = belongYear;
            int lastMonth     = belongMonth;

            if (belongMonth == 1)
            {
                lastYear  = belongYear - 1;
                lastMonth = 12;
            }

            //上月领用单IDs
            var appliedList = this.ComprehensiveDbContext.Set <T_G_GoodsApply>()
                              .Where(d => d.ApplyDate.Value.Year == lastYear &&
                                     d.ApplyDate.Value.Month == lastMonth).ToList();
            var appliedIDs = appliedList.Select(d => d.ID).ToList();

            //当月领用单IDs
            var applyList = this.ComprehensiveDbContext.Set <T_G_GoodsApply>()
                            .Where(d => d.ApplyDate.Value.Year == belongYear &&
                                   d.ApplyDate.Value.Month == belongMonth).ToList();
            var applyIDs = applyList.Select(d => d.ID).ToList();

            foreach (var goodsInfo in goodsInfoList)
            {
                var goodsReport = new R_G_GoodsReport();
                goodsReport.ID          = FormulaHelper.CreateGuid();
                goodsReport.Name        = goodsInfo.Name;
                goodsReport.Model       = goodsInfo.Model;
                goodsReport.Unit        = goodsInfo.Unit;
                goodsReport.Remark      = goodsInfo.Remark;
                goodsReport.GoodsID     = goodsInfo.ID;
                goodsReport.BelongYear  = belongYear;
                goodsReport.BelongMonth = belongMonth;

                //期初数
                int initialCount   = 0;
                var addedGoodsInfo = this.ComprehensiveDbContext.Set <S_G_GoodsAdditional>().Where(d => d.AdditionalData.Value.Year == lastYear &&
                                                                                                   d.AdditionalData.Value.Month == lastMonth &&
                                                                                                   d.Goods == goodsInfo.ID).ToList();
                var addedGoodsSum    = addedGoodsInfo.Sum(d => d.Quantity.HasValue ? d.Quantity.Value : 0);
                var appliedGoodsInfo = this.ComprehensiveDbContext.Set <T_G_GoodsApply_ApplyDetail>().Where(d => appliedIDs.Contains(d.T_G_GoodsApplyID) && d.Goods == goodsInfo.ID).ToList();
                var appliedGoodsSum  = appliedGoodsInfo.Sum(d => d.Quantity.HasValue ? d.Quantity.Value : 0);
                initialCount             = goodsInfo.Quantity.Value + addedGoodsSum - appliedGoodsSum;
                goodsReport.InitialCount = initialCount;

                //库存数
                int stockCount   = 0;
                var addGoodsInfo = this.ComprehensiveDbContext.Set <S_G_GoodsAdditional>().Where(d => d.AdditionalData.Value.Year == belongYear &&
                                                                                                 d.AdditionalData.Value.Month == belongMonth &&
                                                                                                 d.Goods == goodsInfo.ID).ToList();
                var addGoodsSum    = addGoodsInfo.Sum(d => d.Quantity.HasValue ? d.Quantity.Value : 0);
                var applyGoodsList = this.ComprehensiveDbContext.Set <T_G_GoodsApply_ApplyDetail>().Where(d => applyIDs.Contains(d.T_G_GoodsApplyID) && d.Goods == goodsInfo.ID).ToList();
                var applyGoodsSum  = applyGoodsList.Sum(d => d.Quantity.HasValue ? d.Quantity.Value : 0);
                stockCount             = goodsInfo.Quantity.Value + addGoodsSum - applyGoodsSum;
                goodsReport.StockCount = stockCount;

                this.ComprehensiveDbContext.Set <R_G_GoodsReport>().Add(goodsReport);

                //各部门领用数
                foreach (var deptOrg in deptOrgList)
                {
                    var applyDetailInfo = new R_G_GoodsReport_ApplyQuantity();
                    applyDetailInfo.ID                = FormulaHelper.CreateGuid();
                    applyDetailInfo.ApplyDept         = deptOrg.Code;
                    applyDetailInfo.ApplyDeptName     = deptOrg.Name;
                    applyDetailInfo.R_G_GoodsReportID = goodsReport.ID;

                    var applyListByDept = this.ComprehensiveDbContext.Set <T_G_GoodsApply>()
                                          .Where(d => d.ApplyDate.Value.Year == belongYear &&
                                                 d.ApplyDate.Value.Month == belongMonth &&
                                                 d.ApplyDept == deptOrg.Code).ToList();
                    var applyIDsByDept       = applyListByDept.Select(d => d.ID).ToList();
                    var applyGoodsInfoByDept = this.ComprehensiveDbContext.Set <T_G_GoodsApply_ApplyDetail>()
                                               .Where(d => applyIDsByDept.Contains(d.T_G_GoodsApplyID) && d.Goods == goodsInfo.ID).ToList();
                    var applyGoodsSumByDept = applyGoodsInfoByDept.Sum(d => d.Quantity);
                    applyDetailInfo.ApplyQuantity = applyGoodsSumByDept;
                    this.ComprehensiveDbContext.Set <R_G_GoodsReport_ApplyQuantity>().Add(applyDetailInfo);
                }
            }
            this.ComprehensiveDbContext.SaveChanges();
        }
Esempio n. 3
0
        public JsonResult ThisSaveList(string listData, string versionID)
        {
            var list = JsonHelper.ToList(listData);

            PriceValidate(list, versionID);

            foreach (var item in list)
            {
                string dataStateFromUICtrl = item.GetValue("_state").ToLower();
                var    data = this.GetEntityByID <S_C_BOQ_Version_Detail>(item.GetValue("ID"));

                if (dataStateFromUICtrl == "removed")
                {
                    if (data != null)
                    {
                        //删除的数据就是该未发布版(暂存)新增数据
                        //则直接删除数据库数据
                        if (data.ModifyState == "Add")
                        {
                            string id = item.GetValue("ID");
                            entities.Set <S_C_BOQ_Version_Detail>().Delete(a => a.ID == id);
                        }
                        else
                        {
                            string  id  = item.GetValue("BOQID");
                            S_C_BOQ boq = entities.Set <S_C_BOQ>().SingleOrDefault(a => a.ID == id);
                            if (boq != null && boq.Locked)
                            {
                                throw new Formula.Exceptions.BusinessValidationException("【" + item.GetValue("Name") + "】清单已被锁定(应用于计量单中)不能删除");
                            }
                            data.ModifyState = "Remove";
                        }
                    }
                }
                else if (dataStateFromUICtrl == "modified")
                {
                    if (data != null)
                    {
                        string  id  = item.GetValue("BOQID");
                        S_C_BOQ boq = entities.Set <S_C_BOQ>().SingleOrDefault(a => a.ID == id);
                        if (boq != null && boq.Locked)
                        {
                            decimal tmp = 0;
                            if (decimal.TryParse(item.GetValue("Quantity"), out tmp))
                            {
                                if (tmp < boq.CheckQuantityTotal)
                                {
                                    throw new Formula.Exceptions.BusinessValidationException("【" + item.GetValue("Name") + "】清单已经计量" + boq.CheckQuantityTotal + boq.Unit + ",因此不能比这个数值小");
                                }
                            }

                            if (decimal.TryParse(item.GetValue("Price"), out tmp))
                            {
                                if (tmp < boq.CheckPriceTotal)
                                {
                                    throw new Formula.Exceptions.BusinessValidationException("【" + item.GetValue("Name") + "】清单已经计价" + boq.CheckPriceTotal + "元,因此不能比这个数值小");
                                }
                            }
                        }
                        this.UpdateEntity <S_C_BOQ_Version_Detail>(data, item);
                        //Add的部分始终保持为add的state,不能混为修改项
                        //只找normal的state变为modify
                        if (data.ModifyState == "Normal")
                        {
                            data.ModifyState = "Modify";
                        }
                    }
                }
                else if (dataStateFromUICtrl == "added")
                {
                    S_C_BOQ_Version_Detail detail = new S_C_BOQ_Version_Detail();
                    detail.ID        = FormulaHelper.CreateGuid();
                    detail.BOQID     = detail.ID;
                    detail.VersionID = versionID;

                    var details = this.entities.Set <S_C_BOQ_Version_Detail>().Where(a => a.VersionID == versionID).ToList();
                    if (details.Count == 0)
                    {
                        detail.SortIndex = 0;
                    }
                    else
                    {
                        var maxSortIndex = details.Max(c => c.SortIndex);
                        detail.SortIndex = maxSortIndex + 0.001;
                    }

                    detail.Name      = item.GetValue("Name");
                    detail.Code      = item.GetValue("Code");
                    detail.Unit      = item.GetValue("Unit");
                    detail.UnitPrice = 0;
                    detail.Quantity  = 0;
                    detail.Price     = 0;
                    decimal tmp = 0;
                    if (decimal.TryParse(item.GetValue("UnitPrice"), out tmp))
                    {
                        detail.UnitPrice = tmp;
                    }
                    if (decimal.TryParse(item.GetValue("Quantity"), out tmp))
                    {
                        detail.Quantity = tmp;
                    }
                    if (decimal.TryParse(item.GetValue("Price"), out tmp))
                    {
                        detail.Price = tmp;
                    }
                    detail.Property     = item.GetValue("Property");
                    detail.Remark       = item.GetValue("Remark");
                    detail.CreateDate   = DateTime.Now;
                    detail.CreateUserID = CurrentUserInfo.UserID;
                    detail.CreateUser   = CurrentUserInfo.UserName;
                    detail.ModifyState  = "Add";
                    entities.Set <S_C_BOQ_Version_Detail>().Add(detail);
                }
            }
            entities.SaveChanges();
            return(Json(""));
        }
        protected override void OnFlowEnd(T_SP_ContractChange entity, S_WF_InsTaskExec taskExec, S_WF_InsDefRouting routing)
        {
            string tmplCode = Request["TmplCode"];
            var    formInfo = baseEntities.Set <S_UI_Form>().SingleOrDefault(c => c.Code == tmplCode);

            if (formInfo == null)
            {
                throw new Exception("没找到编号为【" + tmplCode + "】的表单定义");
            }
            var sqlContract    = @"select * from S_SP_SupplierContract where ID = '{0}'";
            var sqlChange      = @"select * from T_SP_ContractChange where ID = '{0}'";
            var contract       = MarketSQLDB.ExecuteDataTable(string.Format(sqlContract, entity.ContractID));
            var change         = MarketSQLDB.ExecuteDataTable(string.Format(sqlChange, entity.ID));
            var subTableFields = JsonHelper.ToList(formInfo.Items).Where(c => c.GetValue("ItemType") == "SubTable").ToList();

            foreach (var item in subTableFields)
            {
                var    contractTableName = "S_SP_SupplierContract" + "_" + item.GetValue("Code");
                var    subTableName      = formInfo.TableName + "_" + item.GetValue("Code");
                string subSql            = "SELECT count(0) as TableCount FROM sysobjects WHERE name='{0}'";
                var    obj = Convert.ToInt32(this.MarketSQLDB.ExecuteScalar(String.Format(subSql, contractTableName)));
                if (obj <= 0)
                {
                    continue;
                }
                subSql = "delete from {0} where {1}='{2}'";
                this.MarketSQLDB.ExecuteNonQuery(String.Format(subSql, contractTableName, "S_SP_SupplierContract" + "ID", entity.ContractID));
                subSql = "select * from {0} where {1}='{2}'";
                var data = this.MarketSQLDB.ExecuteDataTable(String.Format(subSql, subTableName, formInfo.TableName + "ID", entity.ID));
                foreach (DataRow subItem in data.Rows)
                {
                    var dic = Formula.FormulaHelper.DataRowToDic(subItem);
                    if (subItem["OrlID"] == null || subItem["OrlID"] == DBNull.Value || String.IsNullOrEmpty(subItem["OrlID"].ToString()))
                    {
                        //表示是新增
                        dic.SetValue("ID", FormulaHelper.CreateGuid());
                    }
                    else
                    {
                        dic.SetValue("ID", subItem["OrlID"]);
                    }
                    dic.SetValue("S_SP_SupplierContractID", entity.ContractID);
                    dic.InsertDB(this.MarketSQLDB, contractTableName, dic.GetValue("ID"));
                }
            }
            var synchList = new List <string>();

            foreach (var column in change.Columns)
            {
                if (!noNeedSynch.Contains(column.ToString()) && contract.Columns.Contains(column.ToString()))
                {
                    synchList.Add(column.ToString());
                }
            }
            var sql    = @"update S_SP_SupplierContract set {0} where ID = '{1}'";
            var setStr = " ";

            foreach (var column in synchList)
            {
                if (column == "SerialNumber")
                {
                    setStr += String.Format("{0} = '{1}',", "SerialNumber", change.Rows[0]["ContractCode"]);
                    continue;
                }
                setStr += String.Format("{0} = '{1}',", column, change.Rows[0][column]);
            }

            sql = string.Format(sql, setStr.TrimEnd(','), entity.ContractID);
            MarketSQLDB.ExecuteNonQuery(sql);
        }
Esempio n. 5
0
        public List <AuditUserInfo> GetAuditSignUser()
        {
            var                  entities        = this.GetDbContext <ProjectEntities>();
            IUserService         service         = FormulaHelper.GetService <IUserService>();
            var                  auditStateArray = Enum.GetNames(typeof(Project.Logic.AuditState));
            var                  activityList    = entities.S_W_Activity.Where(d => d.BusniessID == this.ID).ToList();
            List <AuditUserInfo> list            = new List <AuditUserInfo>();

            var dic = this.ToDic();

            foreach (var item in auditStateArray)
            {
                if (this.AuditSignSource == "0")//从表单上取
                {
                    var value = dic.GetValue(item);
                    if (!string.IsNullOrEmpty(value))
                    {
                        var users = value.Split(',');
                        foreach (var user in users)
                        {
                            var u = service.GetUserInfoByID(user);
                            if (u != null)
                            {
                                AuditUserInfo userInfo = new AuditUserInfo(item, user, u.UserName);
                                userInfo.SignDate = DateTime.Now;
                                list.Add(userInfo);
                            }
                        }
                    }
                }
                else//从流程中取
                {
                    //项目负责人需要按照策划的顺序进行签名
                    if (item == "ProjectManager" && !string.IsNullOrEmpty(this.ProjectManager))
                    {
                        var pms = this.ProjectManager.Split(',');
                        foreach (var pmID in pms)
                        {
                            var activity = activityList.FirstOrDefault(a => a.ActivityKey == item && a.OwnerUserID == pmID);
                            if (activity != null)
                            {
                                AuditUserInfo userInfo = new AuditUserInfo(item, activity.OwnerUserID, activity.OwnerUserName);
                                userInfo.SignDate = activityList.Where(d => d.ActivityKey == item).Max(d => d.CreateDate);
                                list.Add(userInfo);
                            }
                        }
                    }
                    else
                    {
                        foreach (var activity in activityList.Where(d => d.ActivityKey == item).ToList())
                        {
                            if (list.Any(a => a.ActivityKey == item && a.UserID == activity.OwnerUserID))
                            {
                                continue;
                            }
                            AuditUserInfo userInfo = new AuditUserInfo(item, activity.OwnerUserID, activity.OwnerUserName);
                            userInfo.SignDate = activityList.Where(d => d.ActivityKey == item).Max(d => d.CreateDate);
                            list.Add(userInfo);
                        }
                    }
                }
            }

            return(list);
        }
Esempio n. 6
0
        public JsonResult GetExpireList(QueryBuilder qb)
        {
            string sql = "select * from S_DownloadDetail where DownloadExpireDate<'" + DateTime.Now.ToString() + "' and CreateUserID='" + FormulaHelper.GetUserInfo().UserID + "'";
            var    dt  = SQLHelper.CreateSqlHelper(ConnEnum.DocConst).ExecuteDataTable(sql, qb);
            var    gd  = new GridData(dt);

            gd.total = qb.TotolCount;
            return(Json(gd));
        }
Esempio n. 7
0
        public DataTable Calculate(string belongYear, string belongMonth)
        {
            var currentUserInfo = FormulaHelper.GetUserInfo();
            var db       = SQLHelper.CreateSqlHelper(ConnEnum.Market);
            var infrasDB = SQLHelper.CreateSqlHelper(ConnEnum.InfrasBaseConfig);
            var sql      = "SELECT * FROM S_EP_RevenueInfo_Detail WHERE 1<>1";
            var resultDt = db.ExecuteDataTable(sql);

            //获取会计期间
            string realDateFrom         = "";
            string realDateTo           = "";
            string defineMonthPeriodSql = "select * from S_EP_DefineMonthPeriod where Year = {0} and Month = {1}";
            var    defineMonthPeriodDt  = infrasDB.ExecuteDataTable(string.Format(defineMonthPeriodSql, belongYear, belongMonth));

            if (defineMonthPeriodDt.Rows.Count > 0)
            {
                realDateFrom = defineMonthPeriodDt.Rows[0]["StartDate"].ToString();
                realDateTo   = defineMonthPeriodDt.Rows[0]["EndDate"].ToString();
            }
            else
            {
                throw new BusinessException("无法获取会计期间");
            }
            //上一期
            DateTime date = new DateTime(Convert.ToInt32(belongYear), Convert.ToInt32(belongMonth), 1);

            date = date.AddMonths(-1);
            string lastDateYearStr  = date.Year.ToString();
            string lastDateMonthStr = date.Month.ToString();

            #region 节点法计算确认收入
            sql = @"select 
isnull(LastIncomeValue,0) as LastIncomeValue,
progressNode.ProgressScale,S_EP_IncomeUnit.*,ContractValue,progressNode.FactEndDate,
S_EP_CBSNode.ChargerUser,S_EP_CBSNode.ChargerUserName,--S_EP_CBSNode.Area,
S_EP_CBSNode.ChargerDept,S_EP_CBSNode.ChargerDeptName--,S_EP_CBSNode.BusinessType
from 
(select Max(AllIncomeScale) as ProgressScale,IncomeUnitID, max(FactEndDate) as FactEndDate 
from S_EP_IncomeUnit_ProgressNode
where State='{2}' and FactEndDate >= cast('{0}' as datetime) and FactEndDate <= cast('{1}' as datetime) and AllIncomeScale>0
group by IncomeUnitID) progressNode
left join S_EP_IncomeUnit on S_EP_IncomeUnit.ID = progressNode.IncomeUnitID
left join S_EP_CBSNode on S_EP_CBSNode.ID=S_EP_IncomeUnit.CBSNodeID
left join {5}..S_EP_DefineIncome on {5}..S_EP_DefineIncome.ID = S_EP_IncomeUnit.UnitDefineID
left join (select Sum(CurrentIncomeTotalValue) as LastIncomeValue,IncomeUnitID
from S_EP_RevenueInfo_Detail left join S_EP_RevenueInfo on S_EP_RevenueInfoID=S_EP_RevenueInfo.ID
where S_EP_RevenueInfo.IncomeDate<'{0}' and S_EP_RevenueInfo.State<>'{3}'
group by IncomeUnitID) LastIncomeInfo on LastIncomeInfo.IncomeUnitID=S_EP_IncomeUnit.ID
where {5}..S_EP_DefineIncome.IncomeType ='{4}' and ContractValue>0  and (S_EP_CBSNode.IsClosed is null or S_EP_CBSNode.IsClosed != 'true')";
            var inComeUnitDt = db.ExecuteDataTable(string.Format(sql, realDateFrom, realDateTo, "Finish",
                                                                 ModifyState.Removed.ToString(), IncomeType.Progress.ToString(), infrasDB.DbName));
            foreach (DataRow row in inComeUnitDt.Rows)
            {
                var contractValue        = row["ContractValue"] == null || row["ContractValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ContractValue"]);
                var progress             = row["ProgressScale"] == null || row["ProgressScale"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ProgressScale"]);
                var currentTotalValue    = progress / 100 * contractValue;
                var lastIncomeTotalValue = row["LastIncomeValue"] == null || row["LastIncomeValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["LastIncomeValue"]);
                var currentValue         = currentTotalValue - lastIncomeTotalValue;
                if (currentValue == 0)
                {
                    continue;                     //当期收入为0的数据需要过滤掉
                }
                var incomeRow = resultDt.NewRow();
                incomeRow["IncomeUnitID"]            = row["ID"];
                incomeRow["CBSInfoID"]               = row["CBSInfoID"];
                incomeRow["CBSNodeID"]               = row["CBSNodeID"];
                incomeRow["CBSNodeFullID"]           = row["CBSNodeFullID"];
                incomeRow["UnitName"]                = row["Name"];
                incomeRow["UnitCode"]                = row["Code"];
                incomeRow["TotalScale"]              = progress;
                incomeRow["LastIncomeTotalValue"]    = lastIncomeTotalValue;
                incomeRow["IncomeValue"]             = currentValue;
                incomeRow["CurrentIncomeTotalValue"] = currentTotalValue;
                incomeRow["Method"]        = IncomeType.Progress.ToString();
                incomeRow["ContractValue"] = row["ContractValue"];
                incomeRow["FactEndDate"]   = row["FactEndDate"];
                //incomeRow["Area"] = row["Area"];
                //incomeRow["BusinessType"] = row["BusinessType"];
                incomeRow["TaxRate"] = row["TaxRate"];//当期税率
                decimal taxRate = 0;
                decimal.TryParse(row["TaxRate"].ToString(), out taxRate);
                var taxValue   = taxRate * currentValue / (1 + taxRate);
                var clearValue = currentValue - taxValue;
                incomeRow["TaxValue"]         = taxValue;   //当期税金
                incomeRow["ClearIncomeValue"] = clearValue; //当期去税金额
                incomeRow["ChargerDept"]      = row["ChargerDept"];
                incomeRow["ChargerDeptName"]  = row["ChargerDeptName"];
                incomeRow["ChargerUser"]      = row["ChargerUser"];
                incomeRow["ChargerUserName"]  = row["ChargerUserName"];
                resultDt.Rows.Add(incomeRow);
            }
            #endregion

            #region 成本法计算确认收入
            sql = String.Format(@"select isnull(LastIncomeValue,0) as LastIncomeValue, ContractValue, S_EP_IncomeUnit.*,
S_EP_CBSNode.ChargerUser,S_EP_CBSNode.ChargerUserName,--S_EP_CBSNode.Area,
S_EP_CBSNode.ChargerDept,S_EP_CBSNode.ChargerDeptName,--S_EP_CBSNode.BusinessType,
isnull(BudgetValue,0) as BudgetValue
from S_EP_IncomeUnit
left join S_EP_CBSNode on S_EP_CBSNode.ID=S_EP_IncomeUnit.CBSNodeID
left join {3}..S_EP_DefineIncome on {3}..S_EP_DefineIncome.ID = S_EP_IncomeUnit.UnitDefineID
left join (select Sum(CurrentIncomeTotalValue) as LastIncomeValue,IncomeUnitID
from S_EP_RevenueInfo_Detail left join S_EP_RevenueInfo on S_EP_RevenueInfoID=S_EP_RevenueInfo.ID
where S_EP_RevenueInfo.IncomeDate<'{0}' and S_EP_RevenueInfo.State<>'{1}'
group by IncomeUnitID) LastIncomeInfo on LastIncomeInfo.IncomeUnitID=S_EP_IncomeUnit.ID
where {3}..S_EP_DefineIncome.IncomeType ='{2}' and (S_EP_CBSNode.IsClosed is null or S_EP_CBSNode.IsClosed != 'true')",
                                realDateFrom, ModifyState.Removed.ToString(), IncomeType.Cost.ToString(), infrasDB.DbName);
            var incomeUnitOfCostDT = db.ExecuteDataTable(sql);
            if (incomeUnitOfCostDT.Rows.Count > 0)
            {
                sql = String.Format(@"select Sum(TotalPrice) as CostValue,CBSNodeFullID from S_EP_CostInfo
where CostDate<='{0}' group by CBSNodeFullID", realDateTo);
                var costDt   = db.ExecuteDataTable(sql);
                var costList = costDt.AsEnumerable();
                foreach (DataRow row in incomeUnitOfCostDT.Rows)
                {
                    decimal costValue   = 0;
                    var     budgetValue = row["BudgetValue"] == null || row["BudgetValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["BudgetValue"]);
                    if (budgetValue <= 0)
                    {
                        continue;
                    }
                    if (row["CBSNodeFullID"] == null || row["CBSNodeFullID"] == DBNull.Value || String.IsNullOrEmpty(row["CBSNodeFullID"].ToString()))
                    {
                        continue;
                    }
                    var costCalInfo = costList.Where(c => c["CostValue"] != null && c["CostValue"] != DBNull.Value && c["CBSNodeFullID"] != null && c["CBSNodeFullID"] != DBNull.Value &&
                                                     c["CBSNodeFullID"].ToString().StartsWith(row["CBSNodeFullID"].ToString()));
                    if (costCalInfo.Count() == 0)
                    {
                        continue;
                    }
                    costValue = costCalInfo.Sum(c => Convert.ToDecimal(c["CostValue"]));
                    var contractValue = row["ContractValue"] == null || row["ContractValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ContractValue"]);
                    //上一期的累计值lastValue计算
                    var     lastIncomeTotalValue = row["LastIncomeValue"] == null || row["LastIncomeValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["LastIncomeValue"]);
                    decimal progress             = costValue / budgetValue * 100;
                    var     currentTotalValue    = costValue / budgetValue * contractValue;
                    var     currentValue         = currentTotalValue - lastIncomeTotalValue;
                    if (currentValue == 0)
                    {
                        continue;                     //当期收入为0的数据需要过滤掉
                    }
                    var incomeRow = resultDt.NewRow();
                    incomeRow["IncomeUnitID"]            = row["ID"];
                    incomeRow["CBSInfoID"]               = row["CBSInfoID"];
                    incomeRow["CBSNodeID"]               = row["CBSNodeID"];
                    incomeRow["CBSNodeFullID"]           = row["CBSNodeFullID"];
                    incomeRow["UnitName"]                = row["Name"];
                    incomeRow["UnitCode"]                = row["Code"];
                    incomeRow["TotalScale"]              = progress;
                    incomeRow["LastIncomeTotalValue"]    = lastIncomeTotalValue;
                    incomeRow["IncomeValue"]             = currentValue;
                    incomeRow["CurrentIncomeTotalValue"] = currentTotalValue;
                    incomeRow["Method"]        = IncomeType.Cost.ToString();
                    incomeRow["ContractValue"] = row["ContractValue"];
                    //incomeRow["Area"] = row["Area"];
                    //incomeRow["BusinessType"] = row["BusinessType"];
                    incomeRow["TaxRate"] = row["TaxRate"];//当期税率
                    decimal taxRate = 0;
                    decimal.TryParse(row["TaxRate"].ToString(), out taxRate);
                    var taxValue   = taxRate * currentValue / (1 + taxRate);
                    var clearValue = currentValue - taxValue;
                    incomeRow["TaxValue"]         = taxValue;   //当期税金
                    incomeRow["ClearIncomeValue"] = clearValue; //当期去税金额
                    incomeRow["ChargerDept"]      = row["ChargerDept"];
                    incomeRow["ChargerDeptName"]  = row["ChargerDeptName"];
                    incomeRow["ChargerUser"]      = row["ChargerUser"];
                    incomeRow["ChargerUserName"]  = row["ChargerUserName"];
                    resultDt.Rows.Add(incomeRow);
                }
            }
            #endregion

            #region 报量法计算确认收入
            {
                string tmpSql = String.Format(@" select isnull(LastIncomeValue,0) as LastIncomeValue, SubmitInfo.ProgressScale,
S_EP_IncomeUnit.*,ContractValue,SubmitInfo.FactEndDate,
S_EP_CBSNode.ChargerUser,S_EP_CBSNode.ChargerUserName,--S_EP_CBSNode.Area,
S_EP_CBSNode.ChargerDept,S_EP_CBSNode.ChargerDeptName--,S_EP_CBSNode.BusinessType
from (select Sum(CurrentScale) as ProgressScale,IncomeUnitID, max(FactEndDate) as FactEndDate  from S_EP_IncomeSubmit
where FactEndDate <='{1}' group by IncomeUnitID) SubmitInfo
left join S_EP_IncomeUnit on S_EP_IncomeUnit.ID = SubmitInfo.IncomeUnitID
left join S_EP_CBSNode on S_EP_CBSNode.ID=S_EP_IncomeUnit.CBSNodeID
left join (select Sum(CurrentIncomeTotalValue) as LastIncomeValue,IncomeUnitID
from S_EP_RevenueInfo_Detail left join S_EP_RevenueInfo on S_EP_RevenueInfoID=S_EP_RevenueInfo.ID
where S_EP_RevenueInfo.IncomeDate<'{0}' and S_EP_RevenueInfo.State<>'{2}'
group by IncomeUnitID) LastIncomeInfo on LastIncomeInfo.IncomeUnitID=S_EP_IncomeUnit.ID
where ContractValue>0 and (S_EP_CBSNode.IsClosed is null or S_EP_CBSNode.IsClosed != 'true')", realDateFrom, realDateTo, ModifyState.Removed.ToString());

                inComeUnitDt = db.ExecuteDataTable(tmpSql);
                foreach (DataRow row in inComeUnitDt.Rows)
                {
                    var contractValue = row["ContractValue"] == null || row["ContractValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ContractValue"]);
                    var progress      = row["ProgressScale"] == null || row["ProgressScale"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ProgressScale"]);
                    if (progress == 0)
                    {
                        continue;
                    }
                    var currentTotalValue = progress / 100 * contractValue;
                    //上一期的累计值lastValue计算
                    decimal lastValue    = row["LastIncomeValue"] == null || row["LastIncomeValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["LastIncomeValue"]);;
                    var     currentValue = currentTotalValue - lastValue;
                    if (currentValue == 0)
                    {
                        continue;                     //当期收入为0的数据需要过滤掉
                    }
                    var incomeRow = resultDt.NewRow();
                    incomeRow["IncomeUnitID"]            = row["ID"];
                    incomeRow["CBSInfoID"]               = row["CBSInfoID"];
                    incomeRow["CBSNodeID"]               = row["CBSNodeID"];
                    incomeRow["CBSNodeFullID"]           = row["CBSNodeFullID"];
                    incomeRow["UnitName"]                = row["Name"];
                    incomeRow["UnitCode"]                = row["Code"];
                    incomeRow["FactEndDate"]             = row["FactEndDate"];
                    incomeRow["TotalScale"]              = progress;
                    incomeRow["LastIncomeTotalValue"]    = lastValue;
                    incomeRow["IncomeValue"]             = currentValue;
                    incomeRow["CurrentIncomeTotalValue"] = currentTotalValue;
                    incomeRow["Method"]        = IncomeType.Submit.ToString();
                    incomeRow["ContractValue"] = row["ContractValue"];
                    //incomeRow["Area"] = row["Area"];
                    //incomeRow["BusinessType"] = row["BusinessType"];
                    incomeRow["TaxRate"] = row["TaxRate"];//当期税率
                    decimal taxRate = 0;
                    decimal.TryParse(row["TaxRate"].ToString(), out taxRate);
                    var taxValue   = taxRate * currentValue / (1 + taxRate);
                    var clearValue = currentValue - taxValue;
                    incomeRow["TaxValue"]         = taxValue;//当期税金
                    incomeRow["ClearIncomeValue"] = clearValue;
                    incomeRow["ChargerDept"]      = row["ChargerDept"];
                    incomeRow["ChargerDeptName"]  = row["ChargerDeptName"];
                    incomeRow["ChargerUser"]      = row["ChargerUser"];
                    incomeRow["ChargerUserName"]  = row["ChargerUserName"];
                    resultDt.Rows.Add(incomeRow);
                }
            }
            #endregion

            #region 发票申报确认收入
            {
                string tmpSql = @"select isnull(LastIncomeValue,0) as LastIncomeValue,isnull(LastClearIncomeValue,0) as LastClearIncomeValue, SubmitInfo.CurrentTotalValue,SubmitInfo.CurrentTotalClearValue,
S_EP_IncomeUnit.*,ContractValue,
S_EP_CBSNode.ChargerUser,S_EP_CBSNode.ChargerUserName,--S_EP_CBSNode.Area,
S_EP_CBSNode.ChargerDept,S_EP_CBSNode.ChargerDeptName--,S_EP_CBSNode.BusinessType
from (select Sum(CurrentValue) as CurrentTotalValue,Sum(ClearValue) as CurrentTotalClearValue,IncomeUnitID from S_EP_IncomeInvoiceConfirm
where ConfirmDate <='{1}' group by IncomeUnitID) SubmitInfo
left join S_EP_IncomeUnit on S_EP_IncomeUnit.ID = SubmitInfo.IncomeUnitID
left join S_EP_CBSNode on S_EP_CBSNode.ID=S_EP_IncomeUnit.CBSNodeID
left join (select Sum(CurrentIncomeTotalValue) as LastIncomeValue,Sum(ClearIncomeValue) as LastClearIncomeValue,IncomeUnitID
from S_EP_RevenueInfo_Detail left join S_EP_RevenueInfo on S_EP_RevenueInfoID=S_EP_RevenueInfo.ID
where S_EP_RevenueInfo.IncomeDate<'{1}' and S_EP_RevenueInfo.State<>'{2}' and S_EP_RevenueInfo_Detail.Method = '{3}'
group by IncomeUnitID) LastIncomeInfo on LastIncomeInfo.IncomeUnitID=S_EP_IncomeUnit.ID
where ContractValue>0 and (S_EP_CBSNode.IsClosed is null or S_EP_CBSNode.IsClosed != 'true')";

                var dt = db.ExecuteDataTable(string.Format(tmpSql, realDateFrom, realDateTo, ModifyState.Removed.ToString(), IncomeType.Invoice.ToString()));
                foreach (DataRow row in dt.Rows)
                {
                    var contractValue          = row["ContractValue"] == null || row["ContractValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["ContractValue"]);
                    var currentTotalValue      = row["CurrentTotalValue"] == null || row["CurrentTotalValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["CurrentTotalValue"]);
                    var currentTotalClearValue = row["CurrentTotalClearValue"] == null || row["CurrentTotalClearValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["CurrentTotalClearValue"]);
                    var lastIncomeTotalValue   = row["LastIncomeValue"] == null || row["LastIncomeValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["LastIncomeValue"]);
                    var lastClearValue         = row["LastClearIncomeValue"] == null || row["LastClearIncomeValue"] == DBNull.Value ? 0m : Convert.ToDecimal(row["LastClearIncomeValue"]);
                    var currentValue           = currentTotalValue - lastIncomeTotalValue;
                    var currentClearValue      = currentTotalClearValue - lastClearValue;
                    if (contractValue == 0 || currentValue == 0)
                    {
                        continue;                                           //合同未0当期收入为0的数据需要过滤掉
                    }
                    var incomeRow = resultDt.NewRow();
                    incomeRow["IncomeUnitID"]            = row["ID"];
                    incomeRow["CBSInfoID"]               = row["CBSInfoID"];
                    incomeRow["CBSNodeID"]               = row["CBSNodeID"];
                    incomeRow["CBSNodeFullID"]           = row["CBSNodeFullID"];
                    incomeRow["UnitName"]                = row["Name"];
                    incomeRow["UnitCode"]                = row["Code"];
                    incomeRow["TotalScale"]              = ((currentTotalValue / contractValue) * 100).ToString("0.00");
                    incomeRow["LastIncomeTotalValue"]    = lastIncomeTotalValue;
                    incomeRow["IncomeValue"]             = currentValue;
                    incomeRow["CurrentIncomeTotalValue"] = currentTotalValue;
                    incomeRow["Method"]        = IncomeType.Invoice.ToString();
                    incomeRow["ContractValue"] = row["ContractValue"];
                    //incomeRow["Area"] = row["Area"];
                    //incomeRow["BusinessType"] = row["BusinessType"];
                    incomeRow["TaxRate"] = row["TaxRate"];//当期税率
                    decimal taxRate = 0;
                    decimal.TryParse(row["TaxRate"].ToString(), out taxRate);
                    var taxValue = taxRate * currentValue / (1 + taxRate);
                    incomeRow["TaxValue"]         = taxValue;          //当期税金(合同税金非发票税金)
                    incomeRow["ClearIncomeValue"] = currentClearValue; //当期去税金额
                    incomeRow["ChargerDept"]      = row["ChargerDept"];
                    incomeRow["ChargerDeptName"]  = row["ChargerDeptName"];
                    incomeRow["ChargerUser"]      = row["ChargerUser"];
                    incomeRow["ChargerUserName"]  = row["ChargerUserName"];
                    resultDt.Rows.Add(incomeRow);
                }
            }
            #endregion
            return(resultDt);
        }
Esempio n. 8
0
        public void AddWBSChildWithAdo(DataRow parentWBSNode, DataRow childWBSNode, DataTable wbsDt, List <S_T_WBSStructInfo> structList)
        {
            if (!childWBSNode.Table.Columns.Contains("AddState"))
            {
                childWBSNode.Table.Columns.Add("AddState");
            }
            if (parentWBSNode["WBSType"] == null || parentWBSNode["WBSType"] == DBNull.Value || String.IsNullOrEmpty(parentWBSNode["WBSType"].ToString()))
            {
                throw new Formula.Exceptions.BusinessValidationException("必须指定父WBS节点的类型");
            }
            if (childWBSNode["WBSType"] == null || childWBSNode["WBSType"] == DBNull.Value || String.IsNullOrEmpty(childWBSNode["WBSType"].ToString()))
            {
                throw new Formula.Exceptions.BusinessValidationException("必须指定WBS节点的类型");
            }

            var stNode = structList.FirstOrDefault(c => c.Code == parentWBSNode["WBSType"].ToString());

            if (stNode == null)
            {
                throw new Formula.Exceptions.BusinessException("【" + parentWBSNode["Name"].ToString() + "】未获取WBS结构定义对象,无法新增子节点");
            }
            if (!stNode.ValidateChildren(childWBSNode["WBSType"].ToString()))
            {
                throw new Formula.Exceptions.BusinessException("【" + EnumBaseHelper.GetEnumDescription(typeof(WBSNodeType), parentWBSNode["WBSType"].ToString())
                                                               + "】节点下不包含【" + EnumBaseHelper.GetEnumDescription(typeof(WBSNodeType), childWBSNode["WBSType"].ToString()) + "】的子节点定义,无法新增子节点");
            }

            if (childWBSNode["ID"] == null || childWBSNode["ID"] == DBNull.Value || String.IsNullOrEmpty(childWBSNode["ID"].ToString()))
            {
                childWBSNode["ID"] = FormulaHelper.CreateGuid();
            }
            childWBSNode["ProjectInfoID"] = parentWBSNode["ProjectInfoID"];
            childWBSNode["ParentID"]      = parentWBSNode["ID"];
            childWBSNode["PhaseCode"]     = parentWBSNode["PhaseCode"];
            childWBSNode["FullID"]        = parentWBSNode["FullID"].ToString() + "." + childWBSNode["ID"].ToString();
            childWBSNode["Level"]         = childWBSNode["FullID"].ToString().Split('.').Length;
            childWBSNode["WBSStructCode"] = childWBSNode["WBSType"];
            childWBSNode["AddState"]      = true.ToString().ToLower();
            var brothers = wbsDt.AsEnumerable().Where(c => c["ParentID"] != DBNull.Value &&
                                                      c["ParentID"].ToString() == parentWBSNode["ID"].ToString()).ToList();

            if (brothers.Count == 0)
            {
                childWBSNode["CodeIndex"] = 1;
            }
            else
            {
                var maxCodeIndex = brothers.Where(c => c["CodeIndex"] != DBNull.Value && c["CodeIndex"] != null).Max(c => c["CodeIndex"]);
                if (maxCodeIndex != null)
                {
                    childWBSNode["CodeIndex"] = Convert.ToInt32(maxCodeIndex) + 1;
                }
                else
                {
                    childWBSNode["CodeIndex"] = 1;
                }
            }
            childWBSNode["State"] = ProjectCommoneState.Plan.ToString();
            if (childWBSNode["SortIndex"] == null || childWBSNode["SortIndex"] == DBNull.Value || String.IsNullOrEmpty(childWBSNode["SortIndex"].ToString()))
            {
                childWBSNode["SortIndex"] = childWBSNode["FullID"].ToString().Split('.').Length * 1000 + 0;
            }
            if ((childWBSNode["WBSValue"] == null || childWBSNode["WBSValue"] == DBNull.Value || String.IsNullOrEmpty(childWBSNode["WBSValue"].ToString())) &&
                stNode.IsDefineNode)
            {
                throw new Formula.Exceptions.BusinessException("枚举类WBS节点,必须指定WBSValue");
            }

            //获取所有的上级节点,填充WBS类别属性字段
            var ancestors = wbsDt.AsEnumerable().Where(c => childWBSNode["FullID"].ToString().StartsWith(c["FullID"].ToString()));

            foreach (var ancestor in ancestors)
            {
                var fieldName = ancestor["WBSType"].ToString() + "Code";
                if (childWBSNode.Table.Columns.Contains(fieldName))
                {
                    childWBSNode[fieldName] = ancestor["WBSValue"];
                }
            }
            if (childWBSNode.Table.Columns.Contains(childWBSNode["WBSType"].ToString() + "Code"))
            {
                childWBSNode[childWBSNode["WBSType"].ToString() + "Code"] = childWBSNode["WBSValue"];
            }
            wbsDt.Rows.Add(childWBSNode);
        }
        //单个物资到货,自动补到货单,一货一单
        protected override void BeforeSave(Dictionary <string, string> dic, Base.Logic.Domain.S_UI_Form formInfo, bool isNew)
        {
            base.BeforeSave(dic, formInfo, isNew);

            if (!isNew)
            {
                return;
            }

            S_P_Arrival arrival = new S_P_Arrival();

            arrival.ID = FormulaHelper.CreateGuid();

            S_P_ContractInfo_Content content = EPCEntites.Set <S_P_ContractInfo_Content>().Find(dic.GetValue("BomInfo"));

            if (content == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("未找到物资信息");
            }

            decimal quantity = 0;

            decimal.TryParse(dic.GetValue("Quantity"), out quantity);
            if (quantity < 0)
            {
                throw new Formula.Exceptions.BusinessValidationException("到货数量不能为" + quantity);
            }

            //可能多发不判断
            //decimal quantity = 0;
            //decimal.TryParse(dic.GetValue("Quantity"), out quantity);
            //decimal hasArrivalQuantity = EPCEntites.Set<S_P_Arrival_DetailInfo>().Where(a => a.BomInfo == content.ID).ToList().Sum(a => a.Quantity ?? 0);
            //decimal sumRest = content.ContractQuantity ?? 0 - hasArrivalQuantity;
            //if (quantity > sumRest)
            //{
            //    throw new Formula.Exceptions.BusinessValidationException("到货数量超出了剩余数量" + sumRest);
            //}

            arrival.CreateDate          = DateTime.Now;
            arrival.ModifyDate          = DateTime.Now;
            arrival.CreateUserID        = CurrentUserInfo.UserID;
            arrival.CreateUser          = CurrentUserInfo.UserName;
            arrival.ModifyUserID        = CurrentUserInfo.UserID;
            arrival.ModifyUser          = CurrentUserInfo.UserName;
            arrival.OrgID               = CurrentUserInfo.UserOrgID;
            arrival.CompanyID           = CurrentUserInfo.UserCompanyID;
            arrival.FlowPhase           = "Start";
            arrival.StepName            = "";
            arrival.EngineeringInfoName = content.S_P_ContractInfo.EngineeringInfoName; //dic.GetValue("EngineeringInfoName");
            arrival.EngineeringInfoCode = content.S_P_ContractInfo.EngineeringInfoCode; // dic.GetValue("EngineeringInfoCode");
            arrival.ContractInfo        = content.S_P_ContractInfo.ID;                  // dic.GetValue("ContractInfo");
            arrival.ContractInfoName    = content.S_P_ContractInfo.Name;                // dic.GetValue("ContractInfoName");
            arrival.ContractCode        = content.S_P_ContractInfo.SerialNumber;        // dic.GetValue("ContractInfoNum");
            arrival.ArrivalDate         = Convert.ToDateTime(dic.GetValue("ArrivalDate"));
            arrival.CheckUser           = CurrentUserInfo.UserID;
            arrival.CheckUserName       = CurrentUserInfo.UserName;

            var form = baseEntities.Set <S_UI_Form>().Where(c => c.Code == "Arrival").OrderByDescending(c => c.ID).FirstOrDefault(); //获取最新一个版本即可

            if (form == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("表单编号为Arrival不存在!");
            }
            string            SerialNumberSettings = form.SerialNumberSettings;
            var               serialNumberDic      = JsonHelper.ToObject(SerialNumberSettings);
            SerialNumberParam param     = new SerialNumberParam();
            string            tmpl      = serialNumberDic["Tmpl"].ToString();
            string            resetRule = serialNumberDic["ResetRule"].ToString();

            arrival.SerialNumber = SerialNumberHelper.GetSerialNumberString(tmpl, param, resetRule, true);

            arrival.SendFormID        = ""; //没有发货单可关联
            arrival.SendFormIDName    = ""; //同上
            arrival.CheckDate         = DateTime.Now;
            arrival.CheckResult       = ""; //无
            arrival.Register          = CurrentUserInfo.UserID;
            arrival.RegisterName      = CurrentUserInfo.UserName;
            arrival.RegisterDate      = DateTime.Now;
            arrival.Remark            = "来自手机端扫描入库";
            arrival.EngineeringInfoID = content.S_P_ContractInfo.EngineeringInfoID;// dic.GetValue("EngineeringInfoID");
            EPCEntites.Set <S_P_Arrival>().Add(arrival);
            EPCEntites.SaveChanges();

            dic.SetValue("PBomID", content.PBomID);
            dic.SetValue("Code", content.Code);
            dic.SetValue("Sepcification", content.Model);
            dic.SetValue("Unit", content.Unit);
            //dic.SetValue("BomInfo", content.ID);
            dic.SetValue("BomInfoName", content.Name);
            dic.SetValue("Name", content.Name);
            dic.SetValue("S_P_ArrivalID", arrival.ID);
        }
        protected override void BeforeSave(Dictionary <string, string> dic, Base.Logic.Domain.S_UI_Form formInfo, bool isNew)
        {
            var entity = this.GetEntityByID(dic["ID"]);

            if (entity == null)
            {
                entity = new T_SC_SchemeForm();
            }
            var sublist = JsonHelper.ToList(dic.GetValue("SubProjectList"));

            if (dic.ContainsKey("SubProjectList"))
            {
                foreach (var item in sublist)
                {
                    if (String.IsNullOrEmpty(item.GetValue("Code")))
                    {
                        item.SetValue("Code", FormulaHelper.CreateGuid());
                    }
                }
                dic.SetValue("SubProjectList", JsonHelper.ToJson(sublist));
            }
            this.UpdateEntity(entity, dic);

            #region 校验整体专业
            #region 校验成果
            string sql = @"select distinct MajorValue, S_W_WBS.Name MajorName from S_E_Product p
left join S_W_WBS on p.WBSID = S_W_WBS.ID 
where p.ProjectInfoID='{0}' and MajorValue not in ('{1}')";
            sql = string.Format(sql, entity.ProjectInfoID, entity.Major.Replace(",", "','"));
            var dt = this.ProjectSQLDB.ExecuteDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                var msgMajor = "";
                foreach (DataRow item in dt.Rows)
                {
                    msgMajor += item["MajorName"].ToString() + ",";
                }
                throw new Formula.Exceptions.BusinessException("专业【" + msgMajor.TrimEnd(',') + "】已经上传了设计成果,必须选中。");
            }
            #endregion

            #region 校验提资单
            var sqlPutInfo = @"select distinct OutMajorValue, S_W_WBS.Name MajorName from T_EXE_MajorPutInfo p
left join S_W_WBS on p.WBSID = S_W_WBS.ParentID and p.OutMajorValue = S_W_WBS.WBSValue 
where p.ProjectInfoID='{0}' and OutMajorValue not in ('{1}')";
            sqlPutInfo = string.Format(sqlPutInfo, entity.ProjectInfoID, entity.Major.Replace(",", "','"));
            var dtPutInfo = this.ProjectSQLDB.ExecuteDataTable(sqlPutInfo);
            if (dtPutInfo.Rows.Count > 0)
            {
                var msgMajor = "";
                foreach (DataRow item in dtPutInfo.Rows)
                {
                    msgMajor += item["MajorName"].ToString() + ",";
                }
                throw new Formula.Exceptions.BusinessException("专业【" + msgMajor.TrimEnd(',') + "】发起过提资,必须选中。");
            }
            #endregion

            #region 校验共享区
            var sqlShareInfo = @"select distinct p.WBSValue, S_W_WBS.Name MajorName from S_D_ShareInfo p
left join S_W_WBS on p.SubProjectWBSID = S_W_WBS.ParentID and p.WBSValue = S_W_WBS.WBSValue 
where p.ProjectInfoID='{0}' and p.WBSValue not in ('{1}')";
            sqlShareInfo = string.Format(sqlShareInfo, entity.ProjectInfoID, entity.Major.Replace(",", "','"));
            var dtShareInfo = this.ProjectSQLDB.ExecuteDataTable(sqlShareInfo);
            if (dtShareInfo.Rows.Count > 0)
            {
                var msgMajor = "";
                foreach (DataRow item in dtShareInfo.Rows)
                {
                    msgMajor += item["MajorName"].ToString() + ",";
                }
                throw new Formula.Exceptions.BusinessException("专业【" + msgMajor.TrimEnd(',') + "】拥有共享区文件,必须选中。");
            }
            #endregion

            #region 校验专业里程碑
            string        finishState       = ProjectCommoneState.Finish.ToString();
            var           finishMileStones  = this.BusinessEntities.Set <S_P_MileStone>().Where(a => a.ProjectInfoID == entity.ProjectInfoID && a.State == finishState).ToList();
            List <string> msgMileStoneMajor = new List <string>();
            foreach (var item in finishMileStones)
            {
                if (string.IsNullOrEmpty(item.MajorValue) && string.IsNullOrEmpty(item.OutMajorValue))
                {
                    continue;
                }
                if (!entity.Major.Split(',').Contains(item.MajorValue))
                {
                    if (!msgMileStoneMajor.Contains(item.MajorValue))
                    {
                        msgMileStoneMajor.Add(item.MajorValue);
                    }
                }
                if (!string.IsNullOrEmpty(item.OutMajorValue))
                {
                    foreach (var _oMajorValue in item.OutMajorValue.Split(','))
                    {
                        if (string.IsNullOrEmpty(_oMajorValue))
                        {
                            continue;
                        }
                        if (!entity.Major.Split(',').Contains(_oMajorValue))
                        {
                            if (!msgMileStoneMajor.Contains(_oMajorValue))
                            {
                                msgMileStoneMajor.Add(_oMajorValue);
                            }
                        }
                    }
                }
            }
            if (msgMileStoneMajor.Count > 0)
            {
                var enmDef = EnumBaseHelper.GetEnumDef("Project.Major");
                throw new Formula.Exceptions.BusinessException("专业【" + String.Join(",", enmDef.EnumItem.Where(d => msgMileStoneMajor.Contains(d.Code)).Select(d => d.Name)) + "】已经有相关里程碑完成,必须选中。");
            }
            #endregion
            #endregion

            #region 校验子项
            var newsubid       = sublist.Select(t => t.GetValue("Code"));
            var enumSubProject = WBSNodeType.SubProject.ToString();
            var wbsList        = this.BusinessEntities.Set <S_W_WBS>().Where(a => a.ProjectInfoID == entity.ProjectInfoID).ToList();
            var subWBSList     = wbsList.Where(a => a.WBSType == enumSubProject).ToList();
            #region 校验成果
            subWBSList
            .Where(w => !newsubid.Contains(w.WBSValue))
            .ToList()
            .ForEach(t =>
            {
                if (t.HasProducts())
                {
                    throw new Formula.Exceptions.BusinessException("子项【" + t.Name + "】已经有成果图纸,不能删除。");
                }
            });
            #endregion

            var WBSIDList = wbsList.Where(a => newsubid.Contains(a.WBSValue)).Select(a => a.ID).ToList();
            #region 校验提资单
            var putInfoList = this.BusinessEntities.Set <T_EXE_MajorPutInfo>().Where(a => a.ProjectInfoID == entity.ProjectInfoID).ToList();
            var hasPutInfo  = putInfoList.Where(a => !WBSIDList.Contains(a.WBSID)).ToList();
            if (hasPutInfo.Count > 0)
            {
                var name = "";
                for (int i = 0; i < hasPutInfo.Count; i++)
                {
                    var pInfo = hasPutInfo[i];
                    if (!string.IsNullOrEmpty(pInfo.WBSID))
                    {
                        var _wbs = wbsList.FirstOrDefault(a => a.ID == pInfo.WBSID);
                        if (_wbs != null)
                        {
                            var subNode = subWBSList.FirstOrDefault(a => _wbs.FullID.Split('.').Contains(a.ID));
                            if (subNode != null)
                            {
                                name += subNode.Name + ",";
                            }
                        }
                    }
                }
                throw new Formula.Exceptions.BusinessException("子项【" + name.TrimEnd(',') + "】发起过提资,不能删除。");
            }
            #endregion

            #region 校验共享区
            var shareInfoList = this.BusinessEntities.Set <S_D_ShareInfo>().Where(a => a.ProjectInfoID == entity.ProjectInfoID).ToList();
            var hasShareInfo  = shareInfoList.Where(a => !WBSIDList.Contains(a.SubProjectWBSID)).ToList();
            if (hasShareInfo.Count > 0)
            {
                var name = "";
                for (int i = 0; i < hasShareInfo.Count; i++)
                {
                    var sInfo = hasShareInfo[i];
                    if (!string.IsNullOrEmpty(sInfo.SubProjectWBSID))
                    {
                        var _wbs = wbsList.FirstOrDefault(a => a.ID == sInfo.SubProjectWBSID);
                        if (_wbs != null)
                        {
                            var subNode = subWBSList.FirstOrDefault(a => _wbs.FullID.Split('.').Contains(a.ID));
                            if (subNode != null)
                            {
                                name += subNode.Name + ",";
                            }
                        }
                    }
                }
                throw new Formula.Exceptions.BusinessException("子项【" + name.TrimEnd(',') + "】拥有共享区文件,不能删除。");
            }
            #endregion
            #endregion

            #region 校验子项下的专业
            foreach (var subProject in sublist)
            {
                if (!String.IsNullOrEmpty(subProject.GetValue("RBSJson")))
                {
                    var rbsList            = JsonHelper.ToList(subProject.GetValue("RBSJson"));
                    var subProjectWBSValue = subProject.GetValue("Code");
                    var subProjectWBSNode  = wbsList.FirstOrDefault(a => a.WBSValue == subProjectWBSValue);
                    if (subProjectWBSNode == null)
                    {
                        continue;
                    }
                    foreach (var majorNode in rbsList)
                    {
                        if (majorNode.GetValue("Valid") == "0")
                        {
                            var code = majorNode.GetValue("MajorCode");
                            #region 校验成果
                            wbsList
                            .Where(w => w.ParentID == subProjectWBSNode.ID && w.WBSValue == code)
                            .ToList().ForEach(t =>
                            {
                                if (t.HasProducts())
                                {
                                    throw new Formula.Exceptions.BusinessException("子项【" + subProject.GetValue("Name") + "】下的专业【" + t.Name + "】已经有成果图纸,不能删除。");
                                }
                            });
                            #endregion

                            #region 校验提资单
                            var hasPutInfo2 = putInfoList.Where(a => a.WBSID == subProjectWBSNode.ID && a.OutMajorValue == code).ToList();
                            if (hasPutInfo2.Count > 0)
                            {
                                throw new Formula.Exceptions.BusinessException("子项【" + subProject.GetValue("Name") + "】下的专业【" + majorNode.GetValue("MajorName") + "】发起过提资,不能删除。");
                            }
                            #endregion

                            #region 校验共享区
                            var hasShareInfo2 = shareInfoList.Where(a => a.SubProjectWBSID == subProjectWBSNode.ID && a.WBSValue == code).ToList();
                            if (hasShareInfo2.Count > 0)
                            {
                                throw new Formula.Exceptions.BusinessException("子项【" + subProject.GetValue("Name") + "】下的专业【" + majorNode.GetValue("MajorName") + "】拥有共享区文件,不能删除。");
                            }
                            #endregion

                            #region 校验专业里程碑
                            if (finishMileStones.Exists(a => a.WBSID == subProjectWBSNode.ID && (
                                                            (!string.IsNullOrEmpty(a.MajorValue) && a.MajorValue == code) ||
                                                            (!string.IsNullOrEmpty(a.OutMajorValue) && a.OutMajorValue.Split(',').Contains(code))
                                                            )))
                            {
                                throw new Formula.Exceptions.BusinessException("子项【" + subProject.GetValue("Name") + "】下的专业【" + majorNode.GetValue("MajorName") + "】已经有相关里程碑完成,不能删除。");
                            }
                            #endregion
                        }
                    }
                }
            }
            #endregion
        }
Esempio n. 11
0
        public static DataTable ExecuteDataTable(this SQLHelper sqlHelper, string sql, BaseQueryBuilder qb, bool dealOrderby = true)
        {
            string orderby = "";

            if (dealOrderby)
            {
                int index = sql.LastIndexOf(" order by", StringComparison.CurrentCultureIgnoreCase);
                if (index > 0)
                {
                    orderby = sql.Substring(index + " order by".Length);
                    sql     = sql.Substring(0, index);
                }
            }

            SearchCondition authCnd = FormulaHelper.CreateAuthDataFilter();

            #region 处理@参数
            List <SqlParameter> pList = new List <SqlParameter>();
            for (int i = authCnd.Items.Count - 1; i >= 0; i--)
            {
                var item = authCnd.Items[i];
                if (item.Field.StartsWith("@"))
                {
                    authCnd.Items.RemoveAt(i);
                    pList.Add(new SqlParameter(item.Field, item.Value));
                }
            }
            for (int i = qb.Items.Count - 1; i >= 0; i--)
            {
                var item = qb.Items[i];
                if (item.Field.StartsWith("@"))
                {
                    qb.Items.RemoveAt(i);
                    pList.Add(new SqlParameter(item.Field, item.Value));
                }
            }
            #endregion

            if (authCnd.Items.Count > 0)
            {
                sql = string.Format("select * from ({0}) sourceTable1 {1}", sql, authCnd.GetWhereString());
            }

            sql = string.Format("select {2} from ({0}) sourceTable {1}", sql, qb.GetWhereString(), qb.Fields);

            string[] qbSortFields = qb.SortField.Split(',');
            string[] qbSortOrders = qb.SortOrder.Split(',');
            for (int i = 0; i < qbSortFields.Length; i++)
            {
                qbSortFields[i] += " " + qbSortOrders[i];
            }
            string qbOrderBy = string.Join(",", qbSortFields);
            if (orderby == "" || !qb.DefaultSort)
            {
                orderby = qbOrderBy;
            }

            if (qb.PageSize == 0)
            {
                DataTable dt = sqlHelper.ExecuteDataTable(sql + " order by " + orderby, pList.ToArray(), CommandType.Text);
                qb.TotolCount = dt.Rows.Count;
                return(dt);
            }
            else
            {
                object totalCount = sqlHelper.ExecuteScalar(string.Format("select count(1) from ({0}) tableCount", sql), pList.ToArray(), CommandType.Text);
                qb.TotolCount = Convert.ToInt32(totalCount);


                int start = qb.PageIndex * qb.PageSize + 1;
                int end   = start + qb.PageSize - 1;

                sql = string.Format(@"select * from (select tempTable1.*, Row_number() over(order by {1}) as RowNumber from ({0}) tempTable1) tmpTable2 where RowNumber between {2} and {3}", sql, orderby, start, end);

                return(sqlHelper.ExecuteDataTable(sql, pList.ToArray(), CommandType.Text));
            }
        }
 int GetTradePrice()
 {
     return(FormulaHelper.CalculateTradePrice(presentedCost, buildingDiscoveryData.quality, false));
 }
        void UpdateSelection()
        {
            // Update spell list scroller
            spellsListScrollBar.Reset(spellsListBox.RowsDisplayed, spellsListBox.Count, spellsListBox.ScrollIndex);
            spellsListScrollBar.TotalUnits  = spellsListBox.Count;
            spellsListScrollBar.ScrollIndex = spellsListBox.ScrollIndex;

            // Get spell settings selected from player spellbook or offered spells
            EffectBundleSettings spellSettings;

            if (buyMode)
            {
                spellSettings = offeredSpells[spellsListBox.SelectedIndex];

                // The price shown in buy mode is the player casting cost * 4
                int goldCost, spellPointCost;
                FormulaHelper.CalculateTotalEffectCosts(spellSettings.Effects, spellSettings.TargetType, out goldCost, out spellPointCost);
                presentedCost = spellPointCost * 4;

                // Presented cost is halved on Witches Festival holiday
                uint gameMinutes = DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.ToClassicDaggerfallTime();
                int  holidayID   = FormulaHelper.GetHolidayId(gameMinutes, 0);
                if (holidayID == (int)DaggerfallConnect.DFLocation.Holidays.Witches_Festival)
                {
                    presentedCost >>= 1;
                    if (presentedCost == 0)
                    {
                        presentedCost = 1;
                    }
                }

                spellCostLabel.Text = presentedCost.ToString();
            }
            else
            {
                // Get spell and exit if spell index not found
                if (!GameManager.Instance.PlayerEntity.GetSpell(spellsListBox.SelectedIndex, out spellSettings))
                {
                    spellNameLabel.Text = string.Empty;
                    ClearEffectLabels();
                    ShowIcons(false);
                    return;
                }
            }

            // Update spell name label
            spellNameLabel.Text = spellSettings.Name;

            // Update effect labels
            if (spellSettings.Effects != null && spellSettings.Effects.Length > 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    if (i < spellSettings.Effects.Length)
                    {
                        SetEffectLabels(spellSettings.Effects[i].Key, i);
                    }
                    else
                    {
                        SetEffectLabels(string.Empty, i);
                    }
                }
            }
            else
            {
                SetEffectLabels(string.Empty, 0);
                SetEffectLabels(string.Empty, 1);
                SetEffectLabels(string.Empty, 2);
            }

            // Update spell icons
            spellIconPanel.BackgroundTexture        = GetSpellIcon(spellSettings.Icon);
            spellTargetIconPanel.BackgroundTexture  = GetSpellTargetIcon(spellSettings.TargetType);
            spellTargetIconPanel.ToolTipText        = GetTargetTypeDescription(spellSettings.TargetType);
            spellElementIconPanel.BackgroundTexture = GetSpellElementIcon(spellSettings.ElementType);
            spellElementIconPanel.ToolTipText       = GetElementDescription(spellSettings.ElementType);
            ShowIcons(true);
        }
Esempio n. 14
0
        public JsonResult GetTree()
        {
            string fullID = Request["RootFullID"];

            if (fullID == null)
            {
                fullID = "";
            }
            fullID = fullID.Trim(',', ' ');
            SQLHelper sqlHelper = SQLHelper.CreateSqlHelper("Base");

            string sql = string.Format(@"select ID,'' as FullName,Code,case when '{1}'='EN' then isnull(NameEN,Name) else Name end as Name,
            ParentID,FullID,Type,SortIndex,Description from S_A_Org where  FullID like '{0}%' and IsDeleted='0'", fullID, FormulaHelper.GetCurrentLGID());

            if (!string.IsNullOrEmpty(Request["OrgType"]))
            {
                sql += string.Format(" and Type in ('{0}')", Request["OrgType"].Replace(",", "','"));
            }

            SearchCondition cnd = new SearchCondition();

            if (!string.IsNullOrEmpty(Request["CorpID"]))
            {
                cnd.Add("FullID", Formula.QueryMethod.InLike, Request["CorpID"]);
            }

            sql += " order by ParentID,SortIndex";
            var dt = sqlHelper.ExecuteDataTable(sql, cnd);

            //数据量大后加载非常缓慢,故注释此处 by PengPai
            //foreach (DataRow item in dt.Rows)
            //{
            //    var itemFullID = item["FullID"].ToString();
            //    var itemFullIDList = itemFullID.Split('.');
            //    if (itemFullIDList.Length > 1)
            //    {
            //        var ancestorIDs = String.Join(",", itemFullIDList);
            //        var ancestorOrg = dt.Select("ID in ('" + ancestorIDs.Replace(",", "','") + "')", " FullID asc");
            //        var fullName = "";
            //        foreach (DataRow ancestor in ancestorOrg)
            //        {
            //            fullName += ancestor["Name"].ToString() + ".";
            //        }
            //        item["FullName"] = fullName.Trim().TrimEnd('.');
            //    }
            //}
            return(Json(dt, JsonRequestBehavior.AllowGet));
        }
Esempio n. 15
0
        public static void InitMod(bool bedSleeping, bool archery, bool riding, bool encumbrance, bool bandaging, bool shipPorts, bool expulsion, bool climbing, bool weaponSpeed, bool weaponMaterials, bool equipDamage, bool enemyAppearance,
                                   bool purifyPot, bool autoExtinguishLight, bool classicStrDmgBonus, bool variantNpcs)
        {
            Debug.Log("Begin mod init: RoleplayRealism");

            Mod         rrItemsMod      = ModManager.Instance.GetMod("RoleplayRealismItems");
            ModSettings rrItemsSettings = rrItemsMod != null?rrItemsMod.GetSettings() : null;

            if (bedSleeping)
            {
                PlayerActivate.RegisterCustomActivation(mod, 41000, BedActivation);
                PlayerActivate.RegisterCustomActivation(mod, 41001, BedActivation);
                PlayerActivate.RegisterCustomActivation(mod, 41002, BedActivation);
            }

            if (archery)
            {
                // Override adjust to hit and damage formulas
                FormulaHelper.RegisterOverride(mod, "AdjustWeaponHitChanceMod", (Func <DaggerfallEntity, DaggerfallEntity, int, int, DaggerfallUnityItem, int>)AdjustWeaponHitChanceMod);
                FormulaHelper.RegisterOverride(mod, "AdjustWeaponAttackDamage", (Func <DaggerfallEntity, DaggerfallEntity, int, int, DaggerfallUnityItem, int>)AdjustWeaponAttackDamage);
            }

            if (riding)
            {
                GameObject playerAdvGO = GameObject.Find("PlayerAdvanced");
                if (playerAdvGO)
                {
                    EnhancedRiding enhancedRiding = playerAdvGO.AddComponent <EnhancedRiding>();
                    if (enhancedRiding != null)
                    {
                        enhancedRiding.RealisticMovement = mod.GetSettings().GetBool("EnhancedRiding", "RealisticMovement");
                        enhancedRiding.TerrainFollowing  = mod.GetSettings().GetBool("EnhancedRiding", "followTerrainEnabled");
                        enhancedRiding.SetFollowTerrainSoftenFactor(mod.GetSettings().GetInt("EnhancedRiding", "followTerrainSoftenFactor"));
                    }
                }
            }

            if (encumbrance)
            {
                EntityEffectBroker.OnNewMagicRound += EncumbranceEffects_OnNewMagicRound;
            }

            if (rrItemsMod == null && bandaging)
            {
                DaggerfallUnity.Instance.ItemHelper.RegisterItemUseHandler((int)UselessItems2.Bandage, UseBandage);
            }

            if (shipPorts)
            {
                GameManager.Instance.TransportManager.ShipAvailiable = IsShipAvailiable;
            }

            if (expulsion)
            {
                // Register the TG/DB Guild classes
                if (!GuildManager.RegisterCustomGuild(FactionFile.GuildGroups.GeneralPopulace, typeof(ThievesGuildRR)))
                {
                    throw new Exception("GuildGroup GeneralPopulace is already overridden, unable to register ThievesGuildRR guild class.");
                }

                if (!GuildManager.RegisterCustomGuild(FactionFile.GuildGroups.DarkBrotherHood, typeof(DarkBrotherhoodRR)))
                {
                    throw new Exception("GuildGroup DarkBrotherHood is already overridden, unable to register DarkBrotherhoodRR guild class.");
                }
            }

            if (climbing)
            {
                FormulaHelper.RegisterOverride(mod, "CalculateClimbingChance", (Func <PlayerEntity, int, int>)CalculateClimbingChance);
            }

            if (weaponSpeed && (rrItemsSettings == null || !rrItemsSettings.GetBool("Modules", "weaponBalance")))
            {
                FormulaHelper.RegisterOverride(mod, "GetMeleeWeaponAnimTime", (Func <PlayerEntity, WeaponTypes, ItemHands, float>)GetMeleeWeaponAnimTime);
            }

            if (weaponMaterials)
            {
                FormulaHelper.RegisterOverride(mod, "CalculateWeaponToHit", (Func <DaggerfallUnityItem, int>)CalculateWeaponToHit);
            }

            if (equipDamage)
            {
                FormulaHelper.RegisterOverride(mod, "ApplyConditionDamageThroughPhysicalHit", (Func <DaggerfallUnityItem, DaggerfallEntity, int, bool>)ApplyConditionDamageThroughPhysicalHit);
            }

            if (enemyAppearance)
            {
                UpdateEnemyClassAppearances();
            }

            if (purifyPot)
            {
                GameManager.Instance.EntityEffectBroker.RegisterEffectTemplate(new CureDiseaseRR(), true);
            }

            if (autoExtinguishLight)
            {
                PlayerEnterExit.OnTransitionDungeonExterior += OnTransitionToDungeonExterior_ExtinguishLight;
            }

            if (classicStrDmgBonus)
            {
                FormulaHelper.RegisterOverride(mod, "DamageModifier", (Func <int, int>)DamageModifier_classicDisplay);
            }

            if (variantNpcs)
            {
                PlayerEnterExit.OnTransitionInterior += OnTransitionToInterior_VariantNPCsprites;
            }

            // Initialise the FG master quest.
            if (!QuestListsManager.RegisterQuestList("RoleplayRealism"))
            {
                throw new Exception("Quest list name is already in use, unable to register RoleplayRealism quest list.");
            }

            RegisterFactionIds();

            // Add additional data into the quest machine for the quests
            QuestMachine questMachine = GameManager.Instance.QuestMachine;

            questMachine.PlacesTable.AddIntoTable(placesTable);
            questMachine.FactionsTable.AddIntoTable(factionsTable);

            // Register the custom armor service
            Services.RegisterMerchantService(1022, CustomArmorService, "Custom Armor");

            Debug.Log("Finished mod init: RoleplayRealism");
        }
Esempio n. 16
0
        /// <summary>
        /// 获取WBS树形结构,可根据不同视角进行分组切换
        /// </summary>
        /// <param name="projectInfoID">项目ID</param>
        /// <param name="viewType">视角</param>
        /// <param name="majorCode">专业编码</param>
        /// <returns></returns>
        public List <Dictionary <string, object> > GetWBSTree(string projectInfoID, string viewType = "Project", bool includeWork = false, string majorCode = "", bool includeCoop = true)
        {
            var wbsFO = FormulaHelper.CreateFO <WBSFO>();

            return(wbsFO.CreateWBSTree(projectInfoID, viewType, includeWork, majorCode, "", false, includeCoop));
        }
        protected override void OnFlowEnd(T_I_ManagerChange entity, S_WF_InsTaskExec taskExec, S_WF_InsDefRouting routing)
        {
            var updateSql = string.Empty;

            if (string.IsNullOrWhiteSpace(entity.LastVersionID))
            {
                var sql = string.Format(@"select * from T_I_ManagerNominate where ID='{0}' ", entity.ManagerNominateID);
                var dt  = EPCSQLDB.ExecuteDataTable(sql);
                if (dt.Rows.Count == 0)
                {
                    throw new Formula.Exceptions.BusinessValidationException("此项目的项目经理信息不存在,请确认!");
                }
                var firstChange = FormulaHelper.DataRowToDic(dt.Rows[0]);
                firstChange.SetValue("NewManager", firstChange.GetValue("Manager"));
                firstChange.SetValue("NewManagerName", firstChange.GetValue("ManagerName"));
                firstChange.SetValue("ManagerNominateID", firstChange.GetValue("ID"));
                firstChange.SetValue("LastVersionID", string.Empty);
                firstChange.SetValue("FirstOne", "true");
                updateSql += firstChange.CreateInsertSql(EPCSQLDB, "T_I_ManagerChange", FormulaHelper.CreateGuid());
            }
            var managerNominate = entity.ToDic();

            managerNominate.SetValue("FlowPhase", "End");
            managerNominate.SetValue("Manager", managerNominate.GetValue("NewManager"));
            managerNominate.SetValue("ManagerName", managerNominate.GetValue("NewManagerName"));
            updateSql += managerNominate.CreateUpdateSql(EPCSQLDB, "T_I_ManagerNominate", managerNominate.GetValue("ManagerNominateID"));
            EPCSQLDB.ExecuteNonQuery(updateSql);
        }
Esempio n. 18
0
        public static int GetSerialNumber(SerialNumberParam param, SerialNumberResetRule rule = SerialNumberResetRule.YearCode | SerialNumberResetRule.MonthCode, bool applySerialNumber = false)
        {
            #region 转换重复规则

            var mode = new Dictionary <string, string>();
            if (param == null)
            {
                mode.Add("Code", "");
            }
            else
            {
                mode.Add("Code", param.Code);
            }

            if (SerialNumberResetRule.YearCode == (rule | SerialNumberResetRule.YearCode))
            {
                mode.Add("YearCode", DateTime.Now.Year.ToString());
            }
            if (SerialNumberResetRule.MonthCode == (rule | SerialNumberResetRule.MonthCode))
            {
                mode.Add("MonthCode", DateTime.Now.Month.ToString());
            }
            if (SerialNumberResetRule.DayCode == (rule | SerialNumberResetRule.DayCode))
            {
                mode.Add("DayCode", DateTime.Now.Day.ToString());
            }
            if (SerialNumberResetRule.CategoryCode == (rule | SerialNumberResetRule.CategoryCode))
            {
                mode.Add("CategoryCode", param.CategoryCode);
            }
            if (SerialNumberResetRule.SubCategoryCode == (rule | SerialNumberResetRule.SubCategoryCode))
            {
                mode.Add("SubCategoryCode", param.SubCategoryCode);
            }
            if (SerialNumberResetRule.OrderNumCode == (rule | SerialNumberResetRule.OrderNumCode))
            {
                mode.Add("OrderNumCode", param.OrderNumCode);
            }
            if (SerialNumberResetRule.PrjCode == (rule | SerialNumberResetRule.PrjCode))
            {
                mode.Add("PrjCode", param.PrjCode);
            }
            if (SerialNumberResetRule.OrgCode == (rule | SerialNumberResetRule.OrgCode))
            {
                mode.Add("OrgCode", param.OrgCode);
            }
            if (SerialNumberResetRule.UserCode == (rule | SerialNumberResetRule.UserCode))
            {
                mode.Add("UserCode", param.UserCode);
            }

            #endregion

            int number = 0;

            #region 查询流水号
            SQLHelper sqlHelper = SQLHelper.CreateSqlHelper(ConnEnum.Base);
            string    sql       = "select Number from S_UI_SerialNumber where 1=1";
            foreach (var item in mode)
            {
                sql += string.Format(" and {0}='{1}'", item.Key, item.Value);
            }
            object obj = sqlHelper.ExecuteScalar(sql);
            if (obj != null)
            {
                number = Convert.ToInt32(obj);
            }
            number++;
            #endregion

            #region 应用流水号
            if (applySerialNumber)
            {
                if (obj != null)
                {
                    sql = string.Format("update S_UI_SerialNumber set Number='{0}' where 1=1 ", number);
                    foreach (var item in mode)
                    {
                        sql += string.Format(" and {0}='{1}'", item.Key, item.Value);
                    }
                }
                else
                {
                    string fields = "";
                    string values = "";
                    foreach (var item in mode)
                    {
                        fields += "," + item.Key;
                        values += ",'" + item.Value + "'";
                    }

                    sql = string.Format("insert into S_UI_SerialNumber (ID,Number{2}) VALUES('{0}','{1}'{3})"
                                        , FormulaHelper.CreateGuid()
                                        , number
                                        , fields
                                        , values);
                }
                sqlHelper.ExecuteNonQuery(sql);
            }
            #endregion

            return(number);
        }
Esempio n. 19
0
        private void Lend(Dictionary <string, object> row)
        {
            var lendNumber = 0;

            int.TryParse(row.GetValue("LendNumber"), out lendNumber);
            var id           = row.GetValue("ID");
            var borrowDetail = this.entities.Set <S_BorrowDetail>().FirstOrDefault(a => a.ID == id);
            var isNew        = false;

            if (lendNumber > 0)
            {
                #region 部分借阅
                if (borrowDetail == null)
                {
                    if (string.IsNullOrEmpty(id))
                    {
                        id = FormulaHelper.CreateGuid();
                    }
                    borrowDetail = new S_BorrowDetail
                    {
                        ID           = id,
                        SpaceID      = row.GetValue("SpaceID"),
                        SpaceName    = row.GetValue("SpaceName"),
                        DataType     = row.GetValue("DataType"),
                        DetailType   = row.GetValue("DetailType"),
                        RelateID     = row.GetValue("RelateID"),
                        ConfigID     = row.GetValue("ConfigID"),
                        Name         = row.GetValue("Name"),
                        Code         = row.GetValue("Code"),
                        LendUserID   = row.GetValue("LendUserID"),
                        LendUserName = row.GetValue("LendUserName"),
                        LendDeptID   = row.GetValue("LendDeptID"),
                        LendDeptName = row.GetValue("LendDeptName"),
                        ParentID     = row.GetValue("ParentID")
                    };
                    var applyNumber = 0;
                    int.TryParse(row.GetValue("ApplyNumber"), out applyNumber);
                    borrowDetail.ApplyNumber = applyNumber;
                    this.entities.Set <S_BorrowDetail>().Add(borrowDetail);
                    isNew = true;

                    var parent = this.entities.Set <S_BorrowDetail>().FirstOrDefault(a => a.ID == borrowDetail.ParentID);
                    if (parent != null)
                    {
                        parent.HasChild = TrueOrFalse.True.ToString();
                    }
                }
                #endregion
                borrowDetail.LendUserID   = row.GetValue("LendUserID");
                borrowDetail.LendUserName = row.GetValue("LendUserName");
                borrowDetail.LendDeptID   = row.GetValue("LendDeptID");
                borrowDetail.LendDeptName = row.GetValue("LendDeptName");
                borrowDetail.LendNumber   = (borrowDetail.LendNumber ?? 0) + lendNumber;
                if (borrowDetail.LendDate == null)
                {
                    borrowDetail.LendDate         = Convert.ToDateTime(row.GetValue("LendDate"));
                    borrowDetail.BorrowExpireDate = Convert.ToDateTime(row.GetValue("BorrowExpireDate"));
                }
                borrowDetail.BorrowState = BorrowDetailState.ToReturn.ToString();

                if (borrowDetail.DetailType == NodeType.Node.ToString())
                {
                    var space    = DocConfigHelper.CreateConfigSpaceByID(borrowDetail.SpaceID);
                    var nodeInfo = new S_NodeInfo(borrowDetail.RelateID, space);
                    InventoryFO.CreateInventoryLedger(nodeInfo, InventoryType.Lend, 0, (0 - lendNumber),
                                                      borrowDetail.ID, borrowDetail.LendUserID, borrowDetail.LendUserName, EnumBaseHelper.GetEnumDescription(InventoryType.Lend.GetType(), InventoryType.Lend.ToString()) + "份数:" + lendNumber + "份");
                    nodeInfo.DataEntity.SetValue("BorrowState", BorrowReturnState.Borrow.ToString());
                    nodeInfo.Save(false);

                    if (isNew)
                    {
                        borrowDetail.Name = nodeInfo.CreateCarName();
                    }
                }
                else
                {
                    var space    = DocConfigHelper.CreateConfigSpaceByID(borrowDetail.SpaceID);
                    var fileInfo = new S_FileInfo(borrowDetail.RelateID, space);
                    InventoryFO.CreateInventoryLedger(fileInfo, InventoryType.Lend, 0, (0 - lendNumber),
                                                      borrowDetail.ID, borrowDetail.LendUserID, borrowDetail.LendUserName, EnumBaseHelper.GetEnumDescription(InventoryType.Lend.GetType(), InventoryType.Lend.ToString()) + "份数:" + lendNumber + "份");
                    fileInfo.DataEntity.SetValue("BorrowState", BorrowReturnState.Borrow.ToString());
                    fileInfo.Save(false);

                    if (isNew)
                    {
                        borrowDetail.Name = fileInfo.CreateCarName();
                    }
                }
            }
            else if (borrowDetail != null)
            {
                if (borrowDetail.LendDate == null)
                {
                    borrowDetail.LendDate = Convert.ToDateTime(row.GetValue("LendDate"));
                }
                if (borrowDetail.BorrowExpireDate == null)
                {
                    borrowDetail.BorrowExpireDate = Convert.ToDateTime(row.GetValue("BorrowExpireDate"));
                }
            }
        }
Esempio n. 20
0
        public override JsonResult GetList(QueryBuilder qb)
        {
            string sql = "select *,datediff(dd,getdate(),[DownloadExpireDate]) as RemainDay from S_DownloadDetail where DownloadExpireDate>='" + DateTime.Now.ToString() + "' and CreateUserID='" + FormulaHelper.GetUserInfo().UserID + "'";
            var    dt  = this.SqlHelper.ExecuteDataTable(sql, qb);
            var    gd  = new GridData(dt);

            gd.total = qb.TotolCount;
            return(Json(gd));
        }
Esempio n. 21
0
        public void Push()
        {
            var progressNode = this.GetDataDicByID("S_EP_IncomeUnit_ProgressNode", this.ModelDic.GetValue("CurrentProgressNode"));

            if (progressNode == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到对应的节点信息,无法确认节点");
            }
            var incomeUnit = this.GetDataDicByID("S_EP_IncomeUnit", this.ModelDic.GetValue("IncomeUnit"));

            if (incomeUnit == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("没有找到对应的收入单元,无法确认节点");
            }

            string sql = "";
            //为了支持用户可在表单上修改比例,故此处需要与节点数据做比较
            var currentTotalScale = String.IsNullOrEmpty(this.ModelDic.GetValue("TotalScale")) ? 0m : Convert.ToDecimal(this.ModelDic.GetValue("TotalScale"));
            var nodeScale         = String.IsNullOrEmpty(progressNode.GetValue("TotalAllScale")) ? 0m : Convert.ToDecimal(progressNode.GetValue("TotalAllScale"));

            if (nodeScale != currentTotalScale)
            {
                //进度确认单上的比例和节点定义的比例不相同,表示在进度确认过程中,用户手工修改了比例
                //则以手工修改的比例为准,那么下一个节点自动需要扣除多余的比例
                var sd        = currentTotalScale - nodeScale;
                var nextNodes = this.DB.ExecuteDataTable(String.Format(@"select top 1 * from S_EP_IncomeUnit_ProgressNode 
where IncomeUnitID='{0}' and SortIndex>{1}", incomeUnit.GetValue("ID"), progressNode.GetValue("SortIndex")));
                if (nextNodes.Rows.Count > 0)
                {
                    if (nextNodes.Rows[0]["IsIncomeNode"].ToString() == true.ToString())
                    {
                        sql += String.Format(@"UPDATE S_EP_IncomeUnit_ProgressNode SET TotalAllScale=TotalAllScale+({1}),AllIncomeScale=AllIncomeScale+({1}) WHERE ID='{0}'",
                                             nextNodes.Rows[0]["ID"], sd
                                             );
                    }
                    else
                    {
                        sql += String.Format(@"UPDATE S_EP_IncomeUnit_ProgressNode SET =TotalAllScale+({1}) WHERE ID='{0}'",
                                             nextNodes.Rows[0]["ID"], sd);
                    }
                }
                else
                {
                    throw new Formula.Exceptions.BusinessValidationException("最后的节点不能修改确认比例");
                }
            }

            var beforeNodes = this.DB.ExecuteDataTable(String.Format(@"select * from S_EP_IncomeUnit_ProgressNode 
where IncomeUnitID='{0}' and SortIndex<={1} and (State<>'{2}' or State is null )order by sortIndex ", incomeUnit.GetValue("ID"), progressNode.GetValue("SortIndex"), "Finish"));            //优化

            foreach (DataRow node in beforeNodes.Rows)
            {
                if (node["IsIncomeNode"] != DBNull.Value && node["IsIncomeNode"].ToString() == true.ToString().ToLower())
                {
                    this.DB.ExecuteNonQuery(String.Format("UPDATE S_EP_IncomeUnit set TotalScale={0},TotalIncomeScale={0} where ID='{1}'", node["TotalAllScale"], incomeUnit.GetValue("ID")));
                }
                this.DB.ExecuteNonQuery(String.Format("UPDATE S_EP_IncomeUnit_ProgressNode SET FactEndDate='{1}' ,State='Finish' WHERE ID='{0}'", node["ID"],
                                                      String.IsNullOrEmpty(this.ModelDic.GetValue("FactEndDate")) ? DateTime.Now.ToString() : this.ModelDic.GetValue("FactEndDate")
                                                      ));
            }

            if (progressNode.GetValue("IsIncomeNode") == true.ToString().ToLower())
            {
                sql += String.Format("UPDATE S_EP_IncomeUnit set TotalScale={0},TotalIncomeScale={0} where ID='{1}'", currentTotalScale, incomeUnit.GetValue("ID"));
            }
            else
            {
                sql += String.Format("UPDATE S_EP_IncomeUnit set TotalScale={0} where ID='{1}'", currentTotalScale, incomeUnit.GetValue("ID"));
            }

            //如果该单元对应的节点是产值节点则往S_EP_ProductionSettleValue插入数据
            var cbsNodeDt = this.DB.ExecuteDataTable(string.Format(@"select S_EP_CBSNode.*, {0}..S_EP_DefineCBSNode.ProductionUnit from S_EP_CBSNode 
                            inner join {0}..S_EP_DefineCBSNode on {0}..S_EP_DefineCBSNode.ID = S_EP_CBSNode.DefineID where S_EP_CBSNode.ID = '{1}'"
                                                                   , this.InfrasDB.DbName, incomeUnit.GetValue("CBSNodeID")));

            var lastProgressNodeDt = this.DB.ExecuteDataTable(String.Format(@"select top 1 * from S_EP_IncomeUnit_ProgressNode 
where IncomeUnitID='{0}' and SortIndex<{1} order by SortIndex desc", incomeUnit.GetValue("ID"), progressNode.GetValue("SortIndex")));

            if (cbsNodeDt.Rows.Count > 0)
            {
                var cbsNodeRow = cbsNodeDt.Rows[0];
                if (cbsNodeRow["ProductionUnit"].ToString() == "true")
                {
                    var productionUnitDt = this.DB.ExecuteDataTable("select * from S_EP_ProductionUnit where CBSNodeID = '" + cbsNodeRow["ID"].ToString() + "'");
                    if (productionUnitDt.Rows.Count == 0)
                    {
                        throw new Formula.Exceptions.BusinessValidationException("虽然该节点为产值节点,但无法找到产值单元。");
                    }
                    var productionUnitRow = productionUnitDt.Rows[0];

                    var productionSettleValueDic = new Dictionary <string, object>();
                    productionSettleValueDic.SetValue("ID", FormulaHelper.CreateGuid());
                    productionSettleValueDic.SetValue("CBSInfo", cbsNodeRow["CBSInfoID"]);
                    productionSettleValueDic.SetValue("CBSNodeID", cbsNodeRow["ID"]);
                    productionSettleValueDic.SetValue("CBSNodeFullID", cbsNodeRow["FullID"]);
                    productionSettleValueDic.SetValue("ProductionUnitID", productionUnitRow["ID"]);
                    productionSettleValueDic.SetValue("UnitName", productionUnitRow["Name"]);
                    productionSettleValueDic.SetValue("UnitCode", productionUnitRow["Code"]);
                    productionSettleValueDic.SetValue("Method", "收入节点进度确认");
                    if (lastProgressNodeDt.Rows.Count > 0)
                    {
                        productionSettleValueDic.SetValue("LastScale", lastProgressNodeDt.Rows[0]["AllScale"]);
                    }
                    //productionSettleValueDic.SetValue("LastProductionValue", "");//
                    productionSettleValueDic.SetValue("TotalScale", currentTotalScale);
                    //productionSettleValueDic.SetValue("TotalProductionValue", "");//
                    //productionSettleValueDic.SetValue("CurrentProductionValue", "");//
                    productionSettleValueDic.SetValue("ConfirmFormID", this.ModelDic["ID"]);
                    productionSettleValueDic.SetValue("ConfirmDetailID", this.ModelDic["ID"]);
                    productionSettleValueDic.SetValue("FactEndDate", progressNode["FactEndDate"]);
                    productionSettleValueDic.SetValue("ChargerUser", cbsNodeRow["ChargerUser"]);
                    productionSettleValueDic.SetValue("ChargerUserName", cbsNodeRow["ChargerUserName"]);
                    productionSettleValueDic.SetValue("ChargerDept", cbsNodeRow["ChargerDept"]);
                    productionSettleValueDic.SetValue("ChargerDeptName", cbsNodeRow["ChargerDeptName"]);
                    productionSettleValueDic.SetValue("Company", cbsNodeRow["OrgID"]);
                    var companyDt = SQLHelper.CreateSqlHelper(ConnEnum.Base).ExecuteDataTable("select * S_A_Org where ID = '" + cbsNodeRow["OrgID"] + "'");
                    if (companyDt.Rows.Count > 0)
                    {
                        productionSettleValueDic.SetValue("CompanyName", companyDt.Rows[0]["Name"]);
                    }
                    productionSettleValueDic.SetValue("FinishProgressNodeID", progressNode["ID"]);
                    sql += productionSettleValueDic.CreateInsertSql(this.DB, "S_EP_ProductionSettleValue", productionSettleValueDic.GetValue("ID"));
                }
            }
            this.DB.ExecuteNonQuery(sql);
        }
Esempio n. 22
0
        public JsonResult SaveExcelData()
        {
            var    reader   = new System.IO.StreamReader(HttpContext.Request.InputStream);
            string data     = reader.ReadToEnd();
            var    tempdata = JsonConvert.DeserializeObject <Dictionary <string, string> >(data);
            var    list     = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(tempdata["data"]);

            var             vID     = GetQueryString("VersionID");
            S_C_BOQ_Version version = entities.Set <S_C_BOQ_Version>().Find(vID);

            if (version == null)
            {
                throw new Formula.Exceptions.BusinessValidationException("未找到ID为" + vID + "的S_C_BOQ_Version");
            }

            var groups = list.GroupBy(a => a.GetValue("Code")).Select(g => new { g.Key, Counts = g.Count() }).ToList();

            if (groups.Count(a => a.Counts > 1) > 0)
            {
                throw new Formula.Exceptions.BusinessValidationException("编号【" + groups.FirstOrDefault(a => a.Counts > 1).Key + "】重复");
            }

            var details  = this.entities.Set <S_C_BOQ_Version_Detail>().Where(a => a.VersionID == vID).ToList();
            var maxindex = details.Count() == 0 ? 0 : details.Max(a => a.SortIndex);

            foreach (var item in list)
            {
                string code = item.GetValue("Code");
                if (entities.Set <S_C_BOQ_Version_Detail>()
                    .Any(a => a.Code == code))
                {
                    throw new Formula.Exceptions.BusinessValidationException("编号【" + item.GetValue("Code") + "】重复");
                }

                S_C_BOQ_Version_Detail detail = new S_C_BOQ_Version_Detail();
                detail.ID        = FormulaHelper.CreateGuid();
                detail.BOQID     = detail.ID;
                detail.VersionID = version.ID;
                detail.Code      = item.GetValue("Code");
                detail.Name      = item.GetValue("Name");
                detail.Property  = item.GetValue("Property");
                detail.Unit      = item.GetValue("Unit");
                decimal tmp = 0;
                if (decimal.TryParse(item.GetValue("UnitPrice"), out tmp))
                {
                    detail.UnitPrice = tmp;
                }
                if (decimal.TryParse(item.GetValue("Quantity"), out tmp))
                {
                    detail.Quantity = tmp;
                }
                if (decimal.TryParse(item.GetValue("Price"), out tmp))
                {
                    detail.Price = tmp;
                }
                else
                {
                    detail.Price = detail.UnitPrice * detail.Quantity;
                }

                detail.Remark = item.GetValue("Remark");

                detail.CreateDate   = DateTime.Now;
                detail.CreateUserID = CurrentUserInfo.UserID;
                detail.CreateUser   = CurrentUserInfo.UserName;
                detail.ModifyState  = "Add";
                detail.SortIndex    = maxindex + 0.001;
                maxindex            = detail.SortIndex;

                entities.Set <S_C_BOQ_Version_Detail>().Add(detail);
            }

            entities.SaveChanges();
            return(Json("Success"));
        }
Esempio n. 23
0
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="cost"></param>
        /// <returns></returns>
        public S_C_CBS_Cost AddCost(S_C_CBS_Cost cost)
        {
            var user     = FormulaHelper.GetUserInfo();
            var entities = this.GetDbContext <ProjectEntities>();

            if (entities.Entry <S_C_CBS_Cost>(cost).State != System.Data.EntityState.Added &&
                entities.Entry <S_C_CBS_Cost>(cost).State != System.Data.EntityState.Detached)
            {
                throw new Formula.Exceptions.BusinessException("非新增状态的S_C_CBS_Cost对象,无法调用AddCost方法");
            }
            if (String.IsNullOrEmpty(cost.ID))
            {
                cost.ID = FormulaHelper.CreateGuid();
            }
            cost.ProjectInfoID = this.ProjectInfoID;
            cost.CBSFullID     = this.FullID;
            cost.CBSID         = this.ID;
            cost.S_C_CBS       = this;

            if (cost.UnitPrice == null)
            {
                cost.UnitPrice = this.UnitPrice;
            }
            if (cost.Quantity == null)
            {
                cost.Quantity = this.Quantity;
            }
            if (cost.TotalValue == null)
            {
                if (cost.Quantity.HasValue && cost.UnitPrice.HasValue)
                {
                    cost.TotalValue = cost.Quantity.Value * cost.UnitPrice.Value;
                }
            }

            cost.CostDate = DateTime.Now;
            if (string.IsNullOrEmpty(cost.CostUser))
            {
                cost.CostUser = user.UserID;
            }
            if (string.IsNullOrEmpty(cost.CostUserName))
            {
                cost.CostUserName = user.UserName;
            }
            if (cost.BelongYear == null)
            {
                cost.BelongYear = DateTime.Now.Year;
            }
            if (cost.BelongQuarter == null)
            {
                cost.BelongQuarter = (DateTime.Now.Month - 1) / 3 + 1;
            }
            if (cost.BelongMonth == null)
            {
                cost.BelongMonth = DateTime.Now.Month;
            }
            if (string.IsNullOrEmpty(cost.BelongDept))
            {
                cost.BelongDept     = this.S_I_ProjectInfo.ChargeDeptID;
                cost.BelongDeptName = this.S_I_ProjectInfo.ChargeDeptName;
            }
            if (string.IsNullOrEmpty(cost.UserDept))
            {
                cost.UserDept     = user.UserOrgID;
                cost.UserDeptName = user.UserOrgName;
            }

            this.S_C_CBS_Cost.Add(cost);
            entities.S_C_CBS_Cost.Add(cost);
            return(cost);
        }
Esempio n. 24
0
        public static string ReplaceString(string sql, DataRow row = null, Dictionary <string, string> dic = null, Dictionary <string, DataTable> dtDic = null)
        {
            if (string.IsNullOrEmpty(sql))
            {
                return(sql);
            }

            var userService = FormulaHelper.GetService <IUserService>();

            var    user   = FormulaHelper.GetUserInfo();
            Regex  reg    = new Regex("\\{[0-9a-zA-Z_]*\\}");
            string result = reg.Replace(sql, (Match m) =>
            {
                string value = m.Value.Trim('{', '}');
                if (dtDic != null && dtDic.Count > 0)
                {
                    var arr = value.Split('.');
                    if (arr.Length == 1)
                    {
                        if (dtDic.ContainsKey(value)) //默认值为整个表
                        {
                            return(JsonHelper.ToJson(dtDic[value]));
                        }
                    }
                    else if (arr.Length == 2) //默认子编号名.字段名
                    {
                        if (dtDic.ContainsKey(arr[0]))
                        {
                            var dt = dtDic[arr[0]];
                            if (dt.Rows.Count > 0 && dt.Columns.Contains(arr[1]))
                            {
                                return(dt.Rows[0][arr[1]].ToString());
                            }
                        }
                    }
                }
                if (row != null && row.Table.Columns.Contains(value))
                {
                    return(row[value].ToString());
                }
                if (dic != null && dic.ContainsKey(value))
                {
                    return(dic[value]);
                }

                switch (value)
                {
                case Formula.Constant.CurrentUserID:
                    return(user.UserID);

                case Formula.Constant.CurrentUserName:
                    return(user.UserName);

                case Formula.Constant.CurrentUserOrgID:
                    return(user.UserOrgID);

                case Formula.Constant.CurrentUserOrgName:
                    return(user.UserOrgName);

                case Formula.Constant.CurrentUserPrjID:
                    return(user.UserPrjID);

                case Formula.Constant.CurrentUserPrjName:
                    return(user.UserPrjName);

                case "CurrentTime":
                    return(DateTime.Now.ToString());

                case "CurrentDate":
                    return(DateTime.Now.Date.ToString("yyyy-MM-dd"));

                default:
                    return(m.Value);
                }
            });

            return(result);
        }
        protected override void BeforeSave(Dictionary <string, string> dic, Base.Logic.Domain.S_UI_Form formInfo, bool isNew)
        {
            var list        = new List <Dictionary <string, object> >();
            var id          = dic.GetValue("ID");
            var normalValue = 0m;

            if (!string.IsNullOrEmpty(dic.GetValue("NormalValue")))
            {
                normalValue = Convert.ToDecimal(dic.GetValue("NormalValue"));
            }
            var extraValue = 0m;

            if (!string.IsNullOrEmpty(dic.GetValue("AdditionalValue")))
            {
                extraValue = Convert.ToDecimal(dic.GetValue("AdditionalValue"));
            }
            if ((normalValue == 0 && extraValue == 0))
            {
                throw new Formula.Exceptions.BusinessException("每日工时不能为0");
            }
            var user     = FormulaHelper.GetUserInfoByID(dic.GetValue("UserID"));
            var employee = this.ComprehensiveDbContext.Set <S_HR_Employee>().FirstOrDefault(d => d.UserID == user.UserID);
            var fo       = FormulaHelper.CreateFO <WorkHourFO>();
            //根据日期段判断
            var startDate      = dic.GetValue("WorkHourDateStart").Replace("T", " ");
            var endDate        = dic.GetValue("WorkHourDateEnd").Replace("T", " ");
            var projectID      = dic.GetValue("ProjectID");
            var WorkTimeMajor  = dic.GetValue("WorkTimeMajor");
            var SubProjectCode = dic.GetValue("SubProjectCode");
            var MajorCode      = dic.GetValue("MajorCode");
            var WorkContent    = dic.GetValue("WorkContent");
            var dateList       = getWorkHourDate(startDate, endDate);
            //已存在工时数据
            var userID    = dic.GetValue("UserID");
            var existList = this.ComprehensiveDbContext.Set <S_W_UserWorkHour>().Where(a => a.UserID == userID && dateList.Contains(a.WorkHourDate)).ToList();

            foreach (var item in dateList)
            {
                var existNormalValue = existList.Where(a => a.WorkHourDate == item && a.SupplementID != id).Sum(a => a.NormalValue);
                var existExtraValue  = existList.Where(a => a.WorkHourDate == item && a.SupplementID != id).Sum(a => a.AdditionalValue);
                if (!existNormalValue.HasValue)
                {
                    existNormalValue = 0;
                }
                if (!existExtraValue.HasValue)
                {
                    existExtraValue = 0;
                }
                //自动补全正班工日,加班工日不补全
                if ((normalValue + existNormalValue) > NormalHoursMax)
                {
                    normalValue = NormalHoursMax - existNormalValue.Value;
                }
                //throw new Formula.Exceptions.BusinessException("【" + item.ToShortDateString() + "】正常工时不能大于" + NormalHoursMax.ToString());
                if ((extraValue + existExtraValue) > maxExtraHour)
                {
                    throw new Formula.Exceptions.BusinessException("【" + item.ToShortDateString() + "】加班工时不能大于" + maxExtraHour.ToString());
                }

                if ((normalValue == 0 && extraValue == 0))
                {
                    continue;
                }

                var userWorkHour = existList.FirstOrDefault(d => d.SupplementID == id &&
                                                            d.UserID == user.UserID && d.WorkHourDate == item);
                if (userWorkHour == null || ComprehensiveDbContext.Entry <S_W_UserWorkHour>(userWorkHour).State == System.Data.EntityState.Deleted)
                {
                    userWorkHour              = ComprehensiveDbContext.Set <S_W_UserWorkHour>().Create();
                    userWorkHour.ID           = FormulaHelper.CreateGuid();
                    userWorkHour.UserID       = user.UserID;
                    userWorkHour.UserName     = user.UserName;
                    userWorkHour.UserDeptID   = user.UserOrgID;
                    userWorkHour.UserDeptName = user.UserOrgName;
                    userWorkHour.WorkHourDate = item;
                    userWorkHour.UserCode     = user.Code;
                    if (employee != null)
                    {
                        userWorkHour.EmployeeID = employee.ID;
                    }
                    userWorkHour.State         = "Create";
                    userWorkHour.IsConfirm     = "0";
                    userWorkHour.IsStep1       = "0";
                    userWorkHour.IsStep2       = "0";
                    userWorkHour.CreateUser    = CurrentUserInfo.UserName;
                    userWorkHour.CreateUserID  = CurrentUserInfo.UserID;
                    userWorkHour.SupplementID  = id;
                    userWorkHour.BelongMonth   = item.Month;
                    userWorkHour.BelongYear    = item.Year;
                    userWorkHour.BelongQuarter = ((item.Month - 1) / 3) + 1;
                    ComprehensiveDbContext.Set <S_W_UserWorkHour>().Add(userWorkHour);
                }
                if (userWorkHour.State != "Create")
                {
                    continue;
                }
                userWorkHour.ProjectChargerUser     = dic.GetValue("ProjectChargerUser");
                userWorkHour.ProjectChargerUserName = dic.GetValue("ProjectChargerUserName");
                userWorkHour.ProjectCode            = dic.GetValue("ProjectCode");
                userWorkHour.ProjectDept            = dic.GetValue("ProjectDept");
                userWorkHour.ProjectDeptName        = dic.GetValue("ProjectDeptName");
                userWorkHour.ProjectID       = projectID;
                userWorkHour.ProjectName     = dic.GetValue("ProjectName");
                userWorkHour.WorkTimeMajor   = dic.GetValue("WorkTimeMajor");
                userWorkHour.SubProjectCode  = dic.GetValue("SubProjectCode");
                userWorkHour.SubProjectName  = dic.GetValue("SubProjectName");
                userWorkHour.TaskWorkCode    = dic.GetValue("TaskWorkCode");
                userWorkHour.TaskWorkName    = dic.GetValue("TaskWorkName");
                userWorkHour.WorkContent     = dic.GetValue("WorkContent");
                userWorkHour.MajorCode       = dic.GetValue("MajorCode");
                userWorkHour.MajorName       = dic.GetValue("MajorName");
                userWorkHour.WorkHourType    = dic.GetValue("WorkHourType");
                userWorkHour.NormalValue     = normalValue;
                userWorkHour.AdditionalValue = extraValue;
                userWorkHour.WorkHourValue   = normalValue + extraValue;
                userWorkHour.WorkHourDay     = fo.ConvertHourToDay(userWorkHour.WorkHourValue, workHourType, NormalHoursMax);
            }
        }
Esempio n. 26
0
        void Update()
        {
            // Automatically update weapons from inventory when PlayerEntity available
            if (playerEntity != null)
            {
                UpdateHands();
            }
            else
            {
                playerEntity = GameManager.Instance.PlayerEntity;
            }

            // Reset variables if there isn't an attack ongoing
            if (!IsWeaponAttacking())
            {
                // If an attack with a bow just finished, set cooldown
                if (ScreenWeapon.WeaponType == WeaponTypes.Bow && isAttacking)
                {
                    cooldownTime = Time.time + FormulaHelper.GetBowCooldownTime(playerEntity);
                }

                isAttacking        = false;
                isDamageFinished   = false;
                isBowSoundFinished = false;
            }

            // Do nothing while weapon cooldown. Used for bow.
            if (Time.time < cooldownTime)
            {
                return;
            }

            // Do nothing if player paralyzed or is climbing
            if (GameManager.Instance.PlayerEntity.IsParalyzed || GameManager.Instance.ClimbingMotor.IsClimbing)
            {
                ShowWeapons(false);
                return;
            }

            bool doToggleSheath = false;

            // Hide weapons and do nothing if spell is ready or cast animation in progress
            if (GameManager.Instance.PlayerEffectManager)
            {
                if (GameManager.Instance.PlayerEffectManager.HasReadySpell || GameManager.Instance.PlayerSpellCasting.IsPlayingAnim)
                {
                    if (!isAttacking && InputManager.Instance.ActionStarted(InputManager.Actions.ReadyWeapon))
                    {
                        GameManager.Instance.PlayerEffectManager.AbortReadySpell();

                        //if currently unsheathed, then sheath it, so we can give the effect of unsheathing it again
                        if (!Sheathed)
                        {
                            ToggleSheath();
                        }

                        doToggleSheath = true;
                    }
                    else
                    {
                        ShowWeapons(false);
                        return;
                    }
                }
            }

            // Toggle weapon sheath
            if (doToggleSheath || (!isAttacking && InputManager.Instance.ActionStarted(InputManager.Actions.ReadyWeapon)))
            {
                ToggleSheath();
            }

            // Toggle weapon hand
            if (!isAttacking && InputManager.Instance.ActionComplete(InputManager.Actions.SwitchHand))
            {
                ToggleHand();
            }

            // Do nothing if weapon isn't done equipping
            if ((usingRightHand && EquipCountdownRightHand != 0) ||
                (!usingRightHand && EquipCountdownLeftHand != 0))
            {
                ShowWeapons(false);
                return;
            }

            // Do nothing if weapons sheathed
            if (Sheathed)
            {
                ShowWeapons(false);
                return;
            }
            else
            {
                ShowWeapons(true);
            }

            // Do nothing if player has cursor active over large HUD (player is clicking on HUD not clicking to attack)
            if (GameManager.Instance.PlayerMouseLook.cursorActive &&
                DaggerfallUI.Instance.DaggerfallHUD != null &&
                DaggerfallUI.Instance.DaggerfallHUD.LargeHUD.ActiveMouseOverLargeHUD)
            {
                return;
            }

            // Get if bow is equipped
            bool bowEquipped = (ScreenWeapon && ScreenWeapon.WeaponType == WeaponTypes.Bow);

            // Handle beginning a new attack
            if (!isAttacking)
            {
                if (!DaggerfallUnity.Settings.ClickToAttack || bowEquipped)
                {
                    // Reset tracking if user not holding down 'SwingWeapon' button and no attack in progress
                    if (!InputManager.Instance.HasAction(InputManager.Actions.SwingWeapon))
                    {
                        lastAttackHand = Hand.None;
                        _gesture.Clear();
                        return;
                    }
                }
                else
                {
                    // Player must click to attack
                    if (InputManager.Instance.ActionStarted(InputManager.Actions.SwingWeapon))
                    {
                        isClickAttack = true;
                    }
                    else
                    {
                        _gesture.Clear();
                        return;
                    }
                }
            }

            var attackDirection = MouseDirections.None;

            if (!isAttacking)
            {
                if (bowEquipped)
                {
                    // Ensure attack button was released before starting the next attack
                    if (lastAttackHand == Hand.None)
                    {
                        attackDirection = DaggerfallUnity.Settings.BowDrawback ? MouseDirections.Up : MouseDirections.Down; // Force attack without tracking a swing for Bow
                    }
                }
                else if (isClickAttack)
                {
                    attackDirection = (MouseDirections)UnityEngine.Random.Range((int)MouseDirections.Left, (int)MouseDirections.DownRight + 1);
                    isClickAttack   = false;
                }
                else
                {
                    attackDirection = TrackMouseAttack(); // Track swing direction for other weapons
                }
            }
            if (isAttacking && bowEquipped && DaggerfallUnity.Settings.BowDrawback && ScreenWeapon.GetCurrentFrame() == 3)
            {
                if (InputManager.Instance.HasAction(InputManager.Actions.ActivateCenterObject) || ScreenWeapon.GetAnimTime() > MaxBowHeldDrawnSeconds)
                {   // Un-draw the bow without releasing an arrow.
                    ScreenWeapon.ChangeWeaponState(WeaponStates.Idle);
                }
                else if (!InputManager.Instance.HasAction(InputManager.Actions.SwingWeapon))
                {   // Release arrow. Debug.Log("Release arrow!");
                    attackDirection = MouseDirections.Down;
                }
            }

            // Start attack if one has been initiated
            if (attackDirection != MouseDirections.None)
            {
                ExecuteAttacks(attackDirection);
                isAttacking = true;
            }

            // Stop here if no attack is happening
            if (!isAttacking)
            {
                return;
            }

            if (!isBowSoundFinished && ScreenWeapon.WeaponType == WeaponTypes.Bow && ScreenWeapon.GetCurrentFrame() == 4)
            {
                ScreenWeapon.PlaySwingSound();
                isBowSoundFinished = true;

                // Remove arrow
                ItemCollection      playerItems = playerEntity.Items;
                DaggerfallUnityItem arrow       = playerItems.GetItem(ItemGroups.Weapons, (int)Weapons.Arrow);
                playerItems.RemoveOne(arrow);
            }
            else if (!isDamageFinished && ScreenWeapon.GetCurrentFrame() == ScreenWeapon.GetHitFrame())
            {
                // Racial override can suppress optional attack voice
                RacialOverrideEffect racialOverride = GameManager.Instance.PlayerEffectManager.GetRacialOverrideEffect();
                bool suppressCombatVoices           = racialOverride != null && racialOverride.SuppressOptionalCombatVoices;

                // Chance to play attack voice
                if (DaggerfallUnity.Settings.CombatVoices && !suppressCombatVoices && ScreenWeapon.WeaponType != WeaponTypes.Bow && Dice100.SuccessRoll(20))
                {
                    ScreenWeapon.PlayAttackVoice();
                }

                // Transfer damage.
                bool hitEnemy = false;

                // Non-bow weapons
                if (ScreenWeapon.WeaponType != WeaponTypes.Bow)
                {
                    MeleeDamage(ScreenWeapon, out hitEnemy);
                }
                // Bow weapons
                else
                {
                    DaggerfallMissile missile = Instantiate(ArrowMissilePrefab);
                    if (missile)
                    {
                        missile.Caster      = GameManager.Instance.PlayerEntityBehaviour;
                        missile.TargetType  = TargetTypes.SingleTargetAtRange;
                        missile.ElementType = ElementTypes.None;
                        missile.IsArrow     = true;

                        lastBowUsed = usingRightHand ? currentRightHandWeapon : currentLeftHandWeapon;;
                    }
                }

                // Fatigue loss
                playerEntity.DecreaseFatigue(swingWeaponFatigueLoss);

                // Play swing sound if attack didn't hit an enemy.
                if (!hitEnemy && ScreenWeapon.WeaponType != WeaponTypes.Bow)
                {
                    ScreenWeapon.PlaySwingSound();
                }
                else
                {
                    // Tally skills
                    if (ScreenWeapon.WeaponType == WeaponTypes.Melee || ScreenWeapon.WeaponType == WeaponTypes.Werecreature)
                    {
                        playerEntity.TallySkill(DFCareer.Skills.HandToHand, 1);
                    }
                    else if (usingRightHand && (currentRightHandWeapon != null))
                    {
                        playerEntity.TallySkill(currentRightHandWeapon.GetWeaponSkillID(), 1);
                    }
                    else if (currentLeftHandWeapon != null)
                    {
                        playerEntity.TallySkill(currentLeftHandWeapon.GetWeaponSkillID(), 1);
                    }

                    playerEntity.TallySkill(DFCareer.Skills.CriticalStrike, 1);
                }
                isDamageFinished = true;
            }
        }
Esempio n. 27
0
        /// <summary>
        /// 根据人员和项目ID获取该人员所拥有的所有权限入口
        /// </summary>
        /// <param name="userID">人员ID</param>
        /// <param name="projectInfoID">项目ID</param>
        /// <returns>入口集合</returns>
        public List <Entrance> GetEntrance(string userID, string projectInfoID)
        {
            if (String.IsNullOrEmpty(projectInfoID))
            {
                //var userDefault = instanceEnitites.S_I_UserDefaultProjectInfo.FirstOrDefault(d => d.UserID == userID);
                var sqlHelper   = SQLHelper.CreateSqlHelper(ConnEnum.Project);
                var sql         = "select top 1 * from S_I_UserDefaultProjectInfo with(nolock) where UserID='" + userID + @"' 
                            and ProjectInfoID is not null and ProjectInfoID !='' order by ID desc";
                var userDefault = sqlHelper.ExecuteObject <S_I_UserDefaultProjectInfo>(sql);
                if (userDefault != null)
                {
                    projectInfoID = userDefault.ProjectInfoID;
                }
            }
            if (String.IsNullOrEmpty(projectInfoID))
            {
                throw new Formula.Exceptions.BusinessException("空的项目ID无法加载项目管理空间");
            }
            var userService = FormulaHelper.GetService <IUserService>();
            var sysRoles    = userService.GetRoleCodesForUser(userID, Config.Constant.OrgRootID);
            var project     = instanceEnitites.S_I_ProjectInfo.FirstOrDefault(d => d.ID == projectInfoID);

            if (project == null)
            {
                throw new Formula.Exceptions.BusinessException("未能找到ID为【" + projectInfoID + "】的项目信息对象,无法获取空间入口信息");
            }
            if (project.ProjectMode == null)
            {
                throw new Formula.Exceptions.BusinessException("项目【" + project.Name + "】的管理模式对象为空,请未项目指定管理模式");
            }
            var result      = project.GetEntraceBySysRoles(sysRoles);
            var projectList = project.GetEntraceByProjectRoles(project.GetUserOBSRoles(userID));

            foreach (var item in projectList.ToList())
            {
                if (result.Exists(d => d.Code == item.Code))
                {
                    continue;
                }
                result.Add(item);
            }

            var roles = project.GetUserOBSRoles(userID);

            if (!roles.Exists(d => String.IsNullOrEmpty(d.MajorValue)))
            {
                foreach (var item in roles)
                {
                    if (!result.Exists(d => d.Code == item.MajorValue))
                    {
                        result.RemoveWhere(d => d.Code == item.MajorValue);
                    }
                    else
                    {
                        var defaultEntrace = result.FirstOrDefault(d => d.Code == item.MajorValue);
                        foreach (var entrace in result)
                        {
                            entrace.IsDefault = false;
                        }
                        defaultEntrace.IsDefault = true;
                        break;
                    }
                }
            }
            if (!result.Exists(d => d.IsDefault) && result.Count > 0)
            {
                result.FirstOrDefault().IsDefault = true;
            }
            return(result.OrderBy(d => d.SortIndex).ToList());
        }
        public override PayloadCallbackResults?EnchantmentPayloadCallback(EnchantmentPayloadFlags context, EnchantmentParam?param = null, DaggerfallEntityBehaviour sourceEntity = null, DaggerfallEntityBehaviour targetEntity = null, DaggerfallUnityItem sourceItem = null, int sourceDamage = 0)
        {
            base.EnchantmentPayloadCallback(context, param, sourceEntity, targetEntity, sourceItem, sourceDamage);

            // Validate
            if (context != EnchantmentPayloadFlags.Strikes || sourceEntity == null || targetEntity == null || sourceItem == null || sourceDamage == 0)
            {
                return(null);
            }

            // Target can saves vs magic
            if (FormulaHelper.SavingThrow(DFCareer.Elements.Magic, DFCareer.EffectFlags.Magic, targetEntity.Entity, 0) == 0)
            {
                return(null);
            }

            // Find live effect as EnchantmentPayloadCallback is only called on template and we need to change live data
            // Log error and allow effect to continue - but it will not operate fully
            MaceOfMolagBalEffect liveEffect = FindLiveEffect(sourceEntity);

            if (liveEffect == null)
            {
                Debug.LogError("MaceOfMolagBalEffect.EnchantmentPayloadCallback could not find live effect instance on source entity.");
            }

            // Seed random
            Random.InitState(Time.frameCount);

            // "The Mace of Molag Bal drains its victim's spell points and gives them to the bearer.
            // "If the victim has no spell points, he is drained of strength, which is also transferred to the wielder."
            // "Using the Mace of Molag Bal can actually give its bearer more spell points or more strength than he would have fully rested."
            // After considerable testing in classic unable to actually reproduce the first part of this effect (transfer of spell points)
            // Could be down to casters in classic dumping their spell point pool almost immediately, but even backstabs failed to transfer any spell points to wielder
            // Implementing spell point drain as per description rather than based on observation in classic
            // Assuming spell points drained are equal to damage
            // Testing in classic shows that strength increase is always 1-6
            if (targetEntity.Entity.CurrentMagicka > 0)
            {
                // First drain spell points from target
                // Limit drain to available spell points on target
                int spellPointsDrained = targetEntity.Entity.CurrentMagicka - targetEntity.Entity.DecreaseMagicka(sourceDamage);

                // Then raise spell points on source equal to amount drained
                // If this will increase over usual spell point pool amount then increase max to by overflow amount
                int overflow = sourceEntity.Entity.CurrentMagicka + spellPointsDrained - sourceEntity.Entity.MaxMagicka;
                if (overflow > 0)
                {
                    // Immediately set increase to spell point maximum to absorb all spell points drained
                    // This also needs to be set each tick so we accumulate this overflow amount to use in live effect
                    sourceEntity.Entity.ChangeMaxMagickaModifier(overflow);
                    if (liveEffect != null)
                    {
                        liveEffect.currentMaxMagickaIncrease += overflow;
                    }
                }
                sourceEntity.Entity.IncreaseMagicka(spellPointsDrained);
            }
            else
            {
                // If target is out of spell points then drain 1-6 strength from target
                int strengthDrained = Random.Range(1, 7);
                DrainTargetStrength(targetEntity, strengthDrained);

                // Accumulate drain amount as a strength buff in live effect
                // These modifiers are automatically serialized/deserialized as part of effect framework
                if (liveEffect != null)
                {
                    liveEffect.ChangeStatMaxMod(DFCareer.Stats.Strength, strengthDrained);
                    liveEffect.ChangeStatMod(DFCareer.Stats.Strength, strengthDrained);
                }
            }

            // Record last strike time
            if (liveEffect != null)
            {
                liveEffect.lastStrikeTime = DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.ToClassicDaggerfallTime();
            }

            // Durability loss is equal to damage caused
            return(new PayloadCallbackResults()
            {
                durabilityLoss = sourceDamage,
            });
        }
Esempio n. 29
0
        /// <summary>
        /// 获取项目工作区的WBS节点
        /// </summary>
        /// <returns></returns>
        public List <Dictionary <string, object> > GetWorkSpaceWBS(string projectInfoID, string userID, string viewType, string majorCode)
        {
            var result      = new List <Dictionary <string, object> >();
            var projectInfo = this.instanceEnitites.S_I_ProjectInfo.FirstOrDefault(d => d.ID == projectInfoID);

            if (projectInfo == null)
            {
                throw new Formula.Exceptions.BusinessException("未能找到ID为【" + projectInfoID + "】的项目信息对象,无法获得WBS结构");
            }
            var    taskWorkType    = WBSNodeType.Work.ToString();
            var    rootStruct      = projectInfo.ProjectMode.S_T_WBSStructInfo.FirstOrDefault(d => d.Code == WBSNodeType.Project.ToString());
            string defaultViewType = rootStruct.Code + "," + rootStruct.ChildCode;
            var    wbsFo           = FormulaHelper.CreateFO <WBSFO>();

            if (!String.IsNullOrEmpty(majorCode))
            {
                result = wbsFo.CreateWBSTree(projectInfoID, viewType, true, majorCode);
                foreach (var item in result)
                {
                    item.SetValue("HasAuth", TrueOrFalse.False.ToString());
                    var wbsID = item.GetValue("ID");
                    if (String.IsNullOrEmpty(wbsID))
                    {
                        continue;
                    }
                    if (item["RBSLIst"] != null && item["RBSLIst"] is List <S_W_RBS> )
                    {
                        var list = item["RBSLIst"] as List <S_W_RBS>;
                        if (list.Exists(c => c.UserID == userID))
                        {
                            item.SetValue("HasAuth", TrueOrFalse.True.ToString());
                        }
                    }
                    else
                    {
                        var wbs = instanceEnitites.S_W_WBS.Include("S_W_RBS").SingleOrDefault(d => d.ID == wbsID);
                        if (wbs == null)
                        {
                            continue;
                        }
                        if (wbs.S_W_RBS.Count(d => d.UserID == userID) > 0)
                        {
                            item.SetValue("HasAuth", TrueOrFalse.True.ToString());
                        }
                    }
                }
            }
            else
            {
                var wbsList = instanceEnitites.S_W_WBS.Include("S_W_RBS").Where(d => d.ProjectInfoID == projectInfoID).ToList();
                foreach (var item in wbsList)
                {
                    var dic = item.ToDic();
                    dic.SetValue("VirtualID", item.ID);
                    if (item.S_W_RBS.Count(d => d.UserID == userID) > 0)
                    {
                        dic.SetValue("HasAuth", TrueOrFalse.True.ToString());
                    }
                    else
                    {
                        dic.SetValue("HasAuth", TrueOrFalse.False.ToString());
                    }
                    result.Add(dic);
                }
            }
            return(result);
        }
Esempio n. 30
0
        public void SaveNodeAttr(List <Dictionary <string, object> > Attrlist)
        {
            var listconfig = this.ListConfig();
            var sort       = 1;
            var tmpList    = this.S_DOC_NodeAttr.Where(a => a.AttrSort < 10000);

            if (tmpList.Count() > 0)
            {
                sort = tmpList.Max(a => a.AttrSort) + 1;
            }
            foreach (var item in Attrlist)
            {
                var context = this.GetDocConfigContext();
                if (!item.ContainsKey("AttrField") || Tool.IsNullOrEmpty(item["AttrField"]))
                {
                    continue;
                }
                string         fileName = item.GetValue("AttrField");
                S_DOC_NodeAttr entity;
                string         ID = item.GetValue("ID");
                if (!String.IsNullOrEmpty(ID))
                {
                    entity = context.S_DOC_NodeAttr.SingleOrDefault(d => d.ID == ID);
                }
                else
                {
                    entity = this.S_DOC_NodeAttr.FirstOrDefault(d => d.AttrField == fileName);
                    if (entity != null)
                    {
                        throw new Formula.Exceptions.BusinessException("已经存在字段名称为【" + fileName + "】的属性,不能重复添加");
                    }
                }
                if (item.GetValue("IsEnum") == TrueOrFalse.True.ToString() &&
                    string.IsNullOrEmpty(item.GetValue("EnumKey")))
                {
                    throw new Formula.Exceptions.BusinessException("枚举字段【" + item.GetValue("AttrName") + "】必须指定枚举Key");
                }
                if (entity == null)
                {
                    entity          = new S_DOC_NodeAttr();
                    entity.ID       = FormulaHelper.CreateGuid();
                    entity.AttrSort = sort;
                    sort++;
                    entity.SpaceID = this.SpaceID;
                    if (String.IsNullOrEmpty(entity.AttrType))
                    {
                        entity.AttrType = Logic.Domain.AttrType.Custom.ToString();
                    }
                    if (String.IsNullOrEmpty(entity.Visible))
                    {
                        entity.Visible = TrueOrFalse.True.ToString();
                    }
                    if (String.IsNullOrEmpty(entity.Disabled))
                    {
                        entity.Disabled = TrueOrFalse.False.ToString();
                    }
                    if (String.IsNullOrEmpty(entity.FulltextProp))
                    {
                        entity.FulltextProp = TrueOrFalse.False.ToString();
                    }
                    this.S_DOC_NodeAttr.Add(entity);
                }
                Tool.UpdateHashtableInstance <S_DOC_NodeAttr>(entity, item);
            }
        }
 public FormulaController()
 {
     _formulaHelper = new FormulaHelper(new EvaluationService(new EvaluatorEngine(new EvaluatorEngineFlee())),
                                        new FormulaLookupService(), new ServiceClient());
 }