PageRenderTime 46ms CodeModel.GetById 2ms app.highlight 34ms RepoModel.GetById 2ms app.codeStats 0ms

/MITD.PMS.Test/CalculationsTest.cs

https://github.com/ehsmohammadi/HPMS
C# | 982 lines | 835 code | 117 blank | 30 comment | 29 complexity | bb3ee9a098dcf1edda7531de57847cff MD5 | raw file
  1using System;
  2using MITD.PMS.Application;
  3using MITD.PMS.Domain.Model.JobIndices;
  4using MITD.PMS.Domain.Model.Jobs;
  5using Microsoft.VisualStudio.TestTools.UnitTesting;
  6using MITD.PMS.Domain.Model.Calculations;
  7using MITD.PMS.Domain.Model.Periods;
  8using MITD.PMS.Domain.Model.Policies;
  9using MITD.PMS.Domain.Service;
 10using MITD.Data.NH;
 11using MITD.PMS.Persistence.NH;
 12using MITD.Core.RuleEngine.NH;
 13using MITD.PMS.Domain.Model.Employees;
 14using System.Collections.Generic;
 15using MITD.Core.RuleEngine;
 16using MITD.Core;
 17using Castle.Windsor;
 18using MITD.Domain.Repository;
 19using MITD.DataAccess.Config;
 20using MITD.Core.Config;
 21using MITD.Core.RuleEngine.Model;
 22using MITD.PMSAdmin.Persistence.NH;
 23using System.Transactions;
 24using System.Threading.Tasks;
 25using System.Threading;
 26using MITD.PMSAdmin.Domain.Model.CustomFieldTypes;
 27using NHibernate.Linq;
 28using NHibernate;
 29using System.Linq;
 30using MITD.PMS.Domain.Model.JobIndexPoints;
 31using System.Data.SqlClient;
 32using System.Configuration;
 33
 34namespace MITD.PMS.Test
 35{
 36    [TestClass]
 37    public class CalculationsTest
 38    {
 39        EventPublisher publisher = new EventPublisher();
 40
 41        [TestMethod]
 42        public void RuleTest()
 43        {
 44            using (var scope = new TransactionScope())
 45            {
 46                using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["PMSDBConnection"].ConnectionString))
 47                {
 48                    var uows = new MITD.Domain.Repository.UnitOfWorkScope(
 49                      new Data.NH.NHUnitOfWorkFactory(() => PMSAdmin.Persistence.NH.PMSAdminSession.GetSession(con)));
 50
 51                    using (var uow = new NHUnitOfWork(PMSSession.GetSession(con)))
 52                    using (var uow2 = uows.CurrentUnitOfWork)
 53                    {
 54                        con.Open();
 55                        var pmsAdminService = new PMS.ACL.PMSAdmin.PMSAdminService(
 56                            new PMSAdmin.Application.UnitService(new PMSAdmin.Persistence.NH.UnitRepository(uows),
 57                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
 58                            new PMSAdmin.Application.JobService(new PMSAdmin.Persistence.NH.JobRepository(uows),
 59                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
 60                            new PMSAdmin.Application.CustomFieldService(new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
 61                            new PMSAdmin.Application.JobPositionService(new PMSAdmin.Persistence.NH.JobPositionRepository(uows)),
 62                            new PMSAdmin.Application.JobIndexService(new PMSAdmin.Persistence.NH.JobIndexRepository(uows),
 63                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
 64                            new PMSAdmin.Application.UnitIndexService(new PMSAdmin.Persistence.NH.UnitIndexRepository(uows),
 65                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows))
 66                            );
 67                        EventPublisher publisher = new EventPublisher();
 68                        var rep = new PMS.Persistence.NH.EmployeeRepository(uow);
 69                        var periodRep = new PMS.Persistence.NH.PeriodRepository(uow);
 70                        var calcRep = new PMS.Persistence.NH.CalculationRepository(uow);
 71                        var policyRep = new MITD.PMS.Persistence.NH.PolicyRepository(uow, new PolicyConfigurator(
 72                            new RuleBasedPolicyEngineService(new LocatorProvider("PMSDbConnection"), publisher)));
 73                        var provider = new PMS.Application.CalculationDataProvider(rep, pmsAdminService,
 74                            new PMS.Persistence.NH.JobIndexPointRepository(uow));
 75                        var policy = policyRep.GetById(new PolicyId(1));
 76                        var period = periodRep.GetBy(c => c.Active);
 77                        var emp = rep.GetBy(new EmployeeId("150554", period.Id));
 78
 79                        // if period has no calculation 
 80                        var calculation = new Calculation(calcRep.GetNextId(), period, policy, Guid.NewGuid().ToString(), DateTime.Now, "150554");
 81                        calcRep.Add(calculation);
 82                        uow.Commit();
 83
 84                        // if period has calculation , get it by its identifier 
 85                        //var calculation = calcRep.GetById(new CalculationId(1));
 86                        
 87                        MITD.PMSReport.Domain.Model.CalculationData empData;
 88                        var pathNo = 1;
 89                        List<SummaryCalculationPoint> calcList = new List<SummaryCalculationPoint>();
 90                        var session = new CalculatorSession();
 91                        while (pathNo <= 2)
 92                        {
 93                            Utils.Res = new MITD.PMS.RuleContracts.RuleResult();
 94                            session.AddCalculationPoints(calcList);
 95                            session.PathNo = pathNo;
 96                            var data = provider.Provide(emp, out empData, calculation, true, session);
 97                            var rule1 = new Rule10();
 98                            rule1.Execute(data);
 99                            var rule2 = new Rule11();
100                            rule2.Execute(data);
101                            var rule3 = new Rule12();
102                            rule3.Execute(data);
103                            //var rule4 = new Rule13();
104                            //rule4.Execute(data);
105                            var res = provider.Convert(Utils.Res, empData, emp, period, calculation);
106                            calcList = res.CalculationPoints.OfType<SummaryCalculationPoint>().ToList();
107                            var jipRep = new JobIndexPointRepository(uow);
108                            if (res.EmployeePointsForAdd != null)
109                            {
110                                foreach (var point in res.EmployeePointsForAdd)
111                                {
112                                    jipRep.Add(point);
113                                }
114                            }
115                            if (res.EmployeePointsForUpdate != null)
116                            {
117                                foreach (var point in res.EmployeePointsForUpdate)
118                                {
119                                    var employeePoint = jipRep.GetById(point.Key);
120                                    employeePoint.SetValue(point.Value);
121                                }
122                            }
123                            uow.Commit();
124                            pathNo++;
125                        }
126                    }
127                }
128            }
129
130        }
131
132
133        [TestMethod]
134        public void EmployeeProvideDataTest()
135        {
136            var uows = new MITD.Domain.Repository.UnitOfWorkScope(
137              new Data.NH.NHUnitOfWorkFactory(() => PMSAdmin.Persistence.NH.PMSAdminSession.GetSession()));
138
139            using (var uow = new NHUnitOfWork(PMSSession.GetSession()))
140            using (var uow2 = uows.CurrentUnitOfWork)
141            {
142                var pmsAdminService = new PMS.ACL.PMSAdmin.PMSAdminService(
143                    new PMSAdmin.Application.UnitService(new PMSAdmin.Persistence.NH.UnitRepository(uows), new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
144                    new PMSAdmin.Application.JobService(new PMSAdmin.Persistence.NH.JobRepository(uows),
145                        new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
146                    new PMSAdmin.Application.CustomFieldService(new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)),
147                    new PMSAdmin.Application.JobPositionService(new PMSAdmin.Persistence.NH.JobPositionRepository(uows)),
148                    new PMSAdmin.Application.JobIndexService(new PMSAdmin.Persistence.NH.JobIndexRepository(uows),
149                        new PMSAdmin.Persistence.NH.CustomFieldRepository(uows))
150                      ,
151                            new PMSAdmin.Application.UnitIndexService(new PMSAdmin.Persistence.NH.UnitIndexRepository(uows),
152                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)
153                    ));
154                var rep = new PMS.Persistence.NH.EmployeeRepository(uow);
155                var provider = new PMS.Application.CalculationDataProvider(rep, pmsAdminService,
156                    new PMS.Persistence.NH.JobIndexPointRepository(uow));
157                var emp = rep.First();
158                MITD.PMSReport.Domain.Model.CalculationData empData;
159                //var data = provider.Provide(emp, out empData);
160            }
161        }
162
163        [TestMethod]
164        public void EmployeeDataTest()
165        {
166            List<PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType> employeeCftList = new List<CustomFieldType>();
167            List<PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType> jobIndexCftList = new List<CustomFieldType>();
168            List<PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType> jobCftList = new List<CustomFieldType>();
169            List<PMSAdmin.Domain.Model.Jobs.Job> jobList = new List<PMSAdmin.Domain.Model.Jobs.Job>();
170            List<PMSAdmin.Domain.Model.JobIndices.JobIndex> jobIndexList = new List<PMSAdmin.Domain.Model.JobIndices.JobIndex>();
171            List<PMSAdmin.Domain.Model.JobPositions.JobPosition> jobPositionList = new List<PMSAdmin.Domain.Model.JobPositions.JobPosition>();
172            List<PMSAdmin.Domain.Model.Units.Unit> unitList = new List<PMSAdmin.Domain.Model.Units.Unit>();
173            PMSAdmin.Domain.Model.Policies.RuleEngineBasedPolicy policy;
174            Core.RuleEngine.Model.Rule rule;
175            Core.RuleEngine.Model.RuleFunction rf;
176            Period period;
177
178
179            List<PMS.Domain.Model.Jobs.Job> jobInPeriodList = new List<PMS.Domain.Model.Jobs.Job>();
180            List<PMS.Domain.Model.JobIndices.JobIndex> jobIndexInPeriodList = new List<PMS.Domain.Model.JobIndices.JobIndex>();
181            List<PMS.Domain.Model.JobPositions.JobPosition> jobPositionInPeriodList = new List<PMS.Domain.Model.JobPositions.JobPosition>();
182            List<PMS.Domain.Model.Units.Unit> unitInPeriodList = new List<PMS.Domain.Model.Units.Unit>();
183            List<PMS.Domain.Model.Employees.Employee> empList = new List<PMS.Domain.Model.Employees.Employee>();
184
185            #region rule Engine
186            var uows = new MITD.Domain.Repository.UnitOfWorkScope(
187                new Data.NH.NHUnitOfWorkFactory(() =>
188                {
189                    RuleEngineSession.sessionName = "PMSDBConnection";
190                    return Core.RuleEngine.NH.RuleEngineSession.GetSession();
191                }));
192
193            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
194            {
195                var recRep = new Core.RuleEngine.NH.REConfigeRepository(uow);
196                var rec = new Core.RuleEngine.Model.RuleEngineConfigurationItem(
197                    new Core.RuleEngine.Model.RuleEngineConfigurationItemId("RuleTextTemplate"),
198@"
199public class <#classname#> : IRule<CalculationData>
200{
201	public void Execute(CalculationData data)
202	{
203		<#ruletext#>
204	}
205}");
206                recRep.Add(rec);
207                rec = new Core.RuleEngine.Model.RuleEngineConfigurationItem(
208                    new Core.RuleEngine.Model.RuleEngineConfigurationItemId("ReferencedAssemblies"),
209                                        @"System.Core.dll;MITD.Core.RuleEngine.dll;MITD.PMS.RuleContracts.dll");
210                recRep.Add(rec);
211                rec = new Core.RuleEngine.Model.RuleEngineConfigurationItem(
212                    new Core.RuleEngine.Model.RuleEngineConfigurationItemId("LibraryTextTemplate"),
213@"
214using System;
215using System.Collections.Generic;
216using MITD.Core;
217using MITD.Core.RuleEngine;
218using MITD.PMS.RuleContracts;
219using System.Linq;
220using System.Globalization;
221
222namespace MITD.Core.RuleEngine
223{
224
225	public static class Utils
226	{
227		public static RuleResult Res =  new RuleResult();
228		<#functions#>
229	}
230
231	public class RuleResultHelper : IRuleResult<RuleResult>
232	{
233		public RuleResult GetResult()
234		{
235			return Utils.Res;
236		}
237		public void Clear()
238		{
239			Utils.Res = new RuleResult();
240		}
241	}
242
243	<#rules#>
244}");
245                recRep.Add(rec);
246
247                var rfRep = new Core.RuleEngine.NH.RuleFunctionRepository(uow);
248                rf = new RuleFunction(rfRep.GetNextId(), "توابع خطکش پورتر",
249@"
250public static int IndexCount(JobPosition job, string indexCFName, string indexCFValue, string group)
251{
252	return job.Indices.Count(j => j.Key.CustomFields.Any(k => k.Key == indexCFName && k.Value == indexCFValue) && j.Key.Group.DictionaryName == group);
253}
254public static string IndexGroup(KeyValuePair<JobIndex, Dictionary<Employee, Inquiry>> index)
255{
256	return index.Key.Group.DictionaryName;
257}
258
259public static string IndexField(KeyValuePair<JobIndex, Dictionary<Employee, Inquiry>> index, string fieldName)
260{
261	return index.Key.CustomFields[fieldName];
262}
263
264public static RulePoint AddPoint(JobPosition job, KeyValuePair<JobIndex, Dictionary<Employee, Inquiry>> index,
265	string name, decimal value, bool final = false)
266{
267	var res = new RulePoint { Name = name, Value = value, Final = final };
268	if (!Utils.Res.JobResults.Any(j => j.Key == job.DictionaryName))
269		Utils.Res.JobResults.Add(job.DictionaryName, new JobPositionResult());
270	if (!Utils.Res.JobResults[job.DictionaryName].IndexResults.Any(j => j.Key == index.Key.DictionaryName))
271		Utils.Res.JobResults[job.DictionaryName].IndexResults.Add(index.Key.DictionaryName, new List<RulePoint>());
272	Utils.Res.JobResults[job.DictionaryName].IndexResults[index.Key.DictionaryName].Add(res);
273	return res;
274}
275
276public static RulePoint AddPoint(JobPosition job, string name, decimal value, bool final = false)
277{
278	var res = new RulePoint { Name = name, Value = value, Final = final };
279	if (!Utils.Res.JobResults.Any(j => j.Key == job.DictionaryName))
280		Utils.Res.JobResults.Add(job.DictionaryName, new JobPositionResult());
281	Utils.Res.JobResults[job.DictionaryName].Results.Add(res);
282	return res;
283}
284
285public static RulePoint AddPoint(string name, decimal value, bool final = false)
286{
287	var res = new RulePoint { Name = name, Value = value, Final = final };
288	Utils.Res.Results.Add(res);
289	return res;
290}
291
292public static RulePoint GetPoint(JobPosition job, KeyValuePair<JobIndex, Dictionary<Employee, Inquiry>> index, string name)
293{
294	return Utils.Res.JobResults[job.DictionaryName].IndexResults[index.Key.DictionaryName].Single(j=>j.Name==name);
295}
296"
297                );
298                rfRep.Add(rf);
299                var ruleRep = new RuleRepository(uow);
300                rule = new Rule(new RuleId(ruleRep.GetNextId()), "محاسبه امتیاز شاخص ها",
301@"
302//محاسبه تعداد شاخص ها با اهمیت های مختلف
303decimal total = 0;
304int it = 0;
305foreach(var job in data.JobPositions)
306{
307	
308	decimal a1 = Utils.IndexCount(job, ""Importance"", ""1"", ""General"");
309	decimal b1 = Utils.IndexCount(job, ""Importance"", ""3"", ""General"");
310	decimal c1 = Utils.IndexCount(job, ""Importance"", ""5"", ""General"");
311	decimal d1 = Utils.IndexCount(job, ""Importance"", ""7"", ""General"");
312	decimal e1 = Utils.IndexCount(job, ""Importance"", ""9"", ""General"");
313
314	//محاسبه عدد وزنی شاخص های عمومی
315	decimal y1 = 0;
316	decimal n = (9 * a1 + 7 * b1 + 5 * c1 + 3 * d1 + e1);
317	if (n != 0)
318		y1 = 20 / n;
319
320	a1 = 9 * y1;
321	b1 = 7 * y1;
322	c1 = 5 * y1;
323	d1 = 3 * y1;
324	e1 = y1;
325
326	decimal a2 = Utils.IndexCount(job, ""Importance"", ""1"", ""Technical"");
327	decimal b2 = Utils.IndexCount(job, ""Importance"", ""3"", ""Technical"");
328	decimal c2 = Utils.IndexCount(job, ""Importance"", ""5"", ""Technical"");
329	decimal d2 = Utils.IndexCount(job, ""Importance"", ""7"", ""Technical"");
330	decimal e2 = Utils.IndexCount(job, ""Importance"", ""9"", ""Technical"");
331				
332	//محاسبه عدد وزنی شاخص های تخصصی
333	decimal y2 = 0;
334	decimal m = (9 * a2 + 7 * b2 + 5 * c2 + 3 * d2 + e2);
335	if (m != 0)
336		y2 = 80 / m;
337
338	a2 = 9 * y2;
339	b2 = 7 * y2;
340	c2 = 5 * y2;
341	d2 = 3 * y2;
342	e2 = y2;
343
344	decimal a3 = Utils.IndexCount(job, ""Importance"", ""1"", ""Equalizer"");
345	decimal b3 = Utils.IndexCount(job, ""Importance"", ""3"", ""Equalizer"");
346	decimal c3 = Utils.IndexCount(job, ""Importance"", ""5"", ""Equalizer"");
347	decimal d3 = Utils.IndexCount(job, ""Importance"", ""7"", ""Equalizer"");
348	decimal e3 = Utils.IndexCount(job, ""Importance"", ""9"", ""Equalizer"");
349
350	//محاسبه عدد وزنی شاخص های یکسان ساز
351	decimal z = .1m;
352	decimal y3 = 0;
353	decimal o = (9 * a3 + 7 * b3 + 5 * c3 + 3 * d3 + e3);
354	if (o != 0)
355		y3 = z / o;
356
357	a3 = 9 * y3;
358	b3 = 7 * y3;
359	c3 = 5 * y3;
360	d3 = 3 * y3;
361	e3 = y3;
362
363	decimal sum = 0;
364	decimal sum2 = 0;
365	decimal sum3 = 0;
366	Random rnd = new Random();
367	foreach (var index in job.Indices)
368	{
369		if (Utils.IndexGroup(index) == ""General"")
370		{
371			Utils.AddPoint(job, index, ""gross"", Convert.ToDecimal(rnd.NextDouble()));
372
373			if (Utils.IndexField(index, ""Importance"") == ""9"")
374			{
375				sum += Utils.AddPoint(job, index, ""net"", a1 * Utils.GetPoint(job, index, ""gross"").Value).Value;
376			}
377			if (Utils.IndexField(index, ""Importance"") == ""7"")
378			{
379				sum += Utils.AddPoint(job, index, ""net"", b1 * Utils.GetPoint(job, index, ""gross"").Value).Value;
380			}
381			if (Utils.IndexField(index, ""Importance"") == ""5"")
382			{
383				sum += Utils.AddPoint(job, index, ""net"", c1 * Utils.GetPoint(job, index, ""gross"").Value).Value;
384			}
385			if (Utils.IndexField(index, ""Importance"") == ""3"")
386			{
387				sum += Utils.AddPoint(job, index, ""net"", d1 * Utils.GetPoint(job, index, ""gross"").Value).Value;
388			}
389			if (Utils.IndexField(index, ""Importance"") == ""1"")
390			{
391				sum += Utils.AddPoint(job, index, ""net"", e1 * Utils.GetPoint(job, index, ""gross"").Value).Value;
392			}
393		}
394		else if (Utils.IndexGroup(index) == ""Technical"")
395		{
396			Utils.AddPoint(job, index, ""gross"", Convert.ToDecimal(rnd.NextDouble()));
397
398			if (Utils.IndexField(index, ""Importance"") == ""9"")
399			{
400				sum2 += Utils.AddPoint(job, index, ""net"", a2 * Utils.GetPoint(job, index, ""gross"").Value).Value;
401			}
402			if (Utils.IndexField(index, ""Importance"") == ""7"")
403			{
404				sum2 += Utils.AddPoint(job, index, ""net"", b2 * Utils.GetPoint(job, index, ""gross"").Value).Value;
405			}
406			if (Utils.IndexField(index, ""Importance"") == ""5"")
407			{
408				sum2 += Utils.AddPoint(job, index, ""net"", c2 * Utils.GetPoint(job, index, ""gross"").Value).Value;
409			}
410			if (Utils.IndexField(index, ""Importance"") == ""3"")
411			{
412				sum2 += Utils.AddPoint(job, index, ""net"", d2 * Utils.GetPoint(job, index, ""gross"").Value).Value;
413			}
414			if (Utils.IndexField(index, ""Importance"") == ""1"")
415			{
416				sum2 += Utils.AddPoint(job, index, ""net"", e2 * Utils.GetPoint(job, index, ""gross"").Value).Value;
417			}
418		}
419		else if (Utils.IndexGroup(index) == ""Equalizer"")
420		{
421			Utils.AddPoint(job, index, ""gross"", Convert.ToDecimal(rnd.NextDouble()));
422
423			if (Utils.IndexField(index, ""Importance"") == ""9"")
424			{
425				sum3 += Utils.AddPoint(job, index, ""net"", a3 * Utils.GetPoint(job, index, ""gross"").Value).Value;
426			}
427			if (Utils.IndexField(index, ""Importance"") == ""7"")
428			{
429				sum3 += Utils.AddPoint(job, index, ""net"", b3 * Utils.GetPoint(job, index, ""gross"").Value).Value;
430			}
431			if (Utils.IndexField(index, ""Importance"") == ""5"")
432			{
433				sum3 += Utils.AddPoint(job, index, ""net"", c3 * Utils.GetPoint(job, index, ""gross"").Value).Value;
434			}
435			if (Utils.IndexField(index, ""Importance"") == ""3"")
436			{
437				sum3 += Utils.AddPoint(job, index, ""net"", d3 * Utils.GetPoint(job, index, ""gross"").Value).Value;
438			}
439			if (Utils.IndexField(index, ""Importance"") == ""1"")
440			{
441				sum3 += Utils.AddPoint(job, index, ""net"", e3 * Utils.GetPoint(job, index, ""gross"").Value).Value;
442			}
443		}
444	}
445	Utils.AddPoint(job, ""final-general"", sum);
446	Utils.AddPoint(job, ""initial-technical"", sum2);
447	Utils.AddPoint(job, ""final-equalizer"", sum3);
448	sum2 = sum2 * (1 - z / 2 + sum3);
449	Utils.AddPoint(job, ""final-technical"", sum2);
450		sum = Math.Min(sum + sum2 + sum3, 100);
451		Utils.AddPoint(job, ""final-job"", sum);
452		total += sum;
453		it++;
454}
455if (it > 0)
456	Utils.AddPoint(""final"", total / it, true);
457", RuleType.PerCalculation, 1);
458                ruleRep.Add(rule);
459
460                uow.Commit();
461            }
462            #endregion
463
464            #region  PMS Admin
465
466            uows = new MITD.Domain.Repository.UnitOfWorkScope(
467               new Data.NH.NHUnitOfWorkFactory(() =>
468               {
469                   return PMSAdmin.Persistence.NH.PMSAdminSession.GetSession();
470               }));
471
472            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
473            {
474                var cftRep = new PMSAdmin.Persistence.NH.CustomFieldRepository(uow);
475
476                #region Employee CustomFields
477
478                for (int i = 0; i < 10; i++)
479                {
480                    var cft = new PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType(cftRep.GetNextId(),
481                        "فبلد دلخواه کارمند" + i, "EmployeeCft" + i, 0, 100, EntityTypeEnum.Employee, "string");
482                    cftRep.Add(cft);
483                    employeeCftList.Add(cft);
484                }
485
486                #endregion
487
488                #region JobIndex CustomFields Creation
489
490                for (int i = 0; i < 9; i++)
491                {
492                    var cft = new PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType(cftRep.GetNextId(),
493                        "فبلد دلخواه شاخص شغل" + i, "JobIndexCft" + i, 0, 100, EntityTypeEnum.JobIndex, "string");
494                    cftRep.Add(cft);
495                    jobIndexCftList.Add(cft);
496                }
497                var imp = new PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType(cftRep.GetNextId(),
498                    "اهمیت", "Importance", 0, 100, EntityTypeEnum.JobIndex, "string");
499                cftRep.Add(imp);
500                jobIndexCftList.Add(imp);
501
502                #endregion
503
504                #region Job CustomFields Creation
505
506                for (int i = 0; i < 10; i++)
507                {
508                    var cft = new PMSAdmin.Domain.Model.CustomFieldTypes.CustomFieldType(cftRep.GetNextId(),
509                        "فبلد دلخواه شغل" + i, "JobCft" + i, 0, 100, EntityTypeEnum.Job, "string");
510                    cftRep.Add(cft);
511                    jobCftList.Add(cft);
512                }
513
514                #endregion
515
516                var jobRep = new PMSAdmin.Persistence.NH.JobRepository(uow);
517
518                #region Jobs Creation
519
520                for (int i = 0; i < 5; i++)
521                {
522                    var job = new PMSAdmin.Domain.Model.Jobs.Job(jobRep.GetNextId(),
523                        " شغل" + i, "Job" + i);
524                    job.AssignCustomFields(jobCftList.Skip(i * 2).Take(2).ToList());
525                    jobRep.AddJob(job);
526                    jobList.Add(job);
527                }
528
529                #endregion
530
531                var jobPositionRep = new PMSAdmin.Persistence.NH.JobPositionRepository(uow);
532
533                #region JobPositions Creation
534
535                for (int i = 0; i < 5; i++)
536                {
537                    var jobPosition = new PMSAdmin.Domain.Model.JobPositions.JobPosition(jobPositionRep.GetNextId(),
538                        " پست" + i, "JobPosition" + i);
539                    jobPositionRep.Add(jobPosition);
540                    jobPositionList.Add(jobPosition);
541                }
542
543                #endregion
544
545                var unitRep = new PMSAdmin.Persistence.NH.UnitRepository(uow);
546
547                #region Unit Creation
548
549                for (int i = 0; i < 5; i++)
550                {
551                    var unit = new PMSAdmin.Domain.Model.Units.Unit(unitRep.GetNextId(),
552                        " واحد" + i, "Unit" + i);
553                    unitRep.Add(unit);
554                    unitList.Add(unit);
555                }
556
557                #endregion
558
559
560                var jobIndexRep = new PMSAdmin.Persistence.NH.JobIndexRepository(uow);
561
562                #region JobIndexes Creation
563
564                var jobIndexCategory = new PMSAdmin.Domain.Model.JobIndices.JobIndexCategory(jobIndexRep.GetNextId(), null, "دسته شاخص", "JobIndexCategory");
565                jobIndexRep.Add(jobIndexCategory);
566
567                for (int i = 0; i < 5; i++)
568                {
569                    var jobIndex = new PMSAdmin.Domain.Model.JobIndices.JobIndex(jobIndexRep.GetNextId(), jobIndexCategory,
570                        " شاخص شغل" + i, "JobIndex" + i);
571                    var jobIndexCustomFields = jobIndexCftList.Skip(i * 2).Take(2).ToList();
572                    jobIndexCustomFields.Add(jobIndexCftList.Single(j => j.DictionaryName == "Importance"));
573                    jobIndex.AssignCustomFields(jobIndexCustomFields);
574                    jobIndexRep.Add(jobIndex);
575                    jobIndexList.Add(jobIndex);
576                }
577
578                #endregion
579
580                var policyRep = new PMSAdmin.Persistence.NH.PolicyRepository(uow);
581
582                #region Policy Creation
583                policy = new PMSAdmin.Domain.Model.Policies.RuleEngineBasedPolicy(policyRep.GetNextId(),
584                        " خظ کش پرتر", "PorterRulerPolicy");
585                policyRep.Add(policy);
586
587                policy.AssignRule(rule);
588                policy.AssignRuleFunction(rf);
589
590                #endregion
591
592                uow.Commit();
593            }
594
595            #endregion
596
597            uows = new MITD.Domain.Repository.UnitOfWorkScope(
598              new Data.NH.NHUnitOfWorkFactory(() => PMS.Persistence.NH.PMSSession.GetSession()));
599
600            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
601            {
602                var periodRep = new PeriodRepository(uow);
603                var periodManagerService = new PeriodManagerService(periodRep, null, null, null, null, null, null, null, null, null, null, null);
604                #region Period creation
605
606                period = new Period(new PeriodId(periodRep.GetNextId()), Guid.NewGuid().ToString(), DateTime.Now, DateTime.Now,91);
607                period.ChangeActiveStatus(periodManagerService, true);
608                periodRep.Add(period);
609                #endregion
610
611                var jobIndexRep = new PMS.Persistence.NH.JobIndexRepository(uow);
612
613                #region JobIndex Creation
614
615                var jobIndexGroupGenaral = new PMS.Domain.Model.JobIndices.JobIndexGroup(jobIndexRep.GetNextId(), period, null,
616                    "گروه شاخص های عمومی", "General");
617                jobIndexRep.Add(jobIndexGroupGenaral);
618                var jobIndexGroupTechnical = new PMS.Domain.Model.JobIndices.JobIndexGroup(jobIndexRep.GetNextId(), period, null,
619                   "گروه شاخص های تخصصی", "Technical");
620                jobIndexRep.Add(jobIndexGroupTechnical);
621
622                var countjil = jobIndexList.Count();
623                var index = 0;
624                foreach (var itm in jobIndexList.Take(countjil / 2))
625                {
626
627                    var sharedJobIndex =
628                        new PMS.Domain.Model.JobIndices.SharedJobIndex(
629                            new PMS.Domain.Model.JobIndices.SharedJobIndexId(itm.Id.Id), itm.Name,
630                            itm.DictionaryName);
631                    var jobIndex = new PMS.Domain.Model.JobIndices.JobIndex(jobIndexRep.GetNextId(), period,
632                        sharedJobIndex, jobIndexGroupGenaral, index % 2 == 0);
633
634                    var dicSharedCutomField = jobIndexCftList
635                        .Where(j => itm.CustomFieldTypeIdList.Select(i => i.Id).Contains(j.Id.Id)).Select(p =>
636                            new PMS.Domain.Model.JobIndices.SharedJobIndexCustomField(
637                                new PMS.Domain.Model.JobIndices.SharedJobIndexCustomFieldId(p.Id.Id), p.Name,
638                                p.DictionaryName,
639                                p.MinValue, p.MaxValue)).ToDictionary(s => s, s => s.DictionaryName == "Importance" ? (((index + 1) * 2) - 1).ToString() : string.Empty);
640
641                    jobIndex.UpdateCustomFields(dicSharedCutomField);
642                    jobIndexInPeriodList.Add(jobIndex);
643                    jobIndexRep.Add(jobIndex);
644                    index++;
645
646                }
647                index = 0;
648                foreach (var itm in jobIndexList.Skip(countjil / 2))
649                {
650                    var sharedJobIndex =
651                        new PMS.Domain.Model.JobIndices.SharedJobIndex(
652                            new PMS.Domain.Model.JobIndices.SharedJobIndexId(itm.Id.Id), itm.Name,
653                            itm.DictionaryName);
654                    var jobIndex = new PMS.Domain.Model.JobIndices.JobIndex(jobIndexRep.GetNextId(), period,
655                        sharedJobIndex, jobIndexGroupTechnical, index % 2 == 0);
656                    var dicSharedCutomField = jobIndexCftList
657                        .Where(j => itm.CustomFieldTypeIdList.Select(i => i.Id).Contains(j.Id.Id)).Select(p =>
658                            new PMS.Domain.Model.JobIndices.SharedJobIndexCustomField(
659                                new PMS.Domain.Model.JobIndices.SharedJobIndexCustomFieldId(p.Id.Id), p.Name,
660                                p.DictionaryName,
661                                p.MinValue, p.MaxValue)).ToDictionary(s => s, s => s.DictionaryName == "Importance" ? (((index + 1) * 2) - 1).ToString() : string.Empty);
662
663                    jobIndex.UpdateCustomFields(dicSharedCutomField);
664
665                    jobIndexInPeriodList.Add(jobIndex);
666                    jobIndexRep.Add(jobIndex);
667                    index++;
668
669                }
670                #endregion
671
672                var jobRep = new PMS.Persistence.NH.JobRepository(uow);
673
674                #region Job creation
675
676                foreach (var pmsAdminJob in jobList)
677                {
678                    var jobJobIndices = jobIndexInPeriodList.Select(jobIndex => new JobJobIndex(jobIndex.Id, true, true, true)).ToList();
679                    var job = new PMS.Domain.Model.Jobs.Job(period, new PMS.Domain.Model.Jobs.SharedJob(
680                        new PMS.Domain.Model.Jobs.SharedJobId(pmsAdminJob.Id.Id), pmsAdminJob.Name, pmsAdminJob.DictionaryName), jobCftList
681                        .Where(j => pmsAdminJob.CustomFieldTypeIdList.Select(i => i.Id)
682                            .Contains(j.Id.Id)).Select(p =>
683                                new PMS.Domain.Model.Jobs.JobCustomField(new PMS.Domain.Model.Jobs.JobCustomFieldId(period.Id, new SharedJobCustomFieldId(p.Id.Id), new SharedJobId(pmsAdminJob.Id.Id))
684                                    , new SharedJobCustomField(new SharedJobCustomFieldId(p.Id.Id), p.Name, p.DictionaryName, p.MinValue, p.MaxValue, p.TypeId))).ToList(), jobJobIndices);
685                    jobInPeriodList.Add(job);
686                    jobRep.Add(job);
687                }
688                #endregion
689
690                var unitRep = new PMS.Persistence.NH.UnitRepository(uow);
691
692                #region Unit Creation
693
694                foreach (var pmsAdminUnit in unitList)
695                {
696                    var unit = new PMS.Domain.Model.Units.Unit(period, new PMS.Domain.Model.Units.SharedUnit(
697                        new PMS.Domain.Model.Units.SharedUnitId(pmsAdminUnit.Id.Id), pmsAdminUnit.Name, pmsAdminUnit.DictionaryName), null);
698                    unitInPeriodList.Add(unit);
699                    unitRep.Add(unit);
700                }
701                #endregion
702
703                var jobPositionRep = new PMS.Persistence.NH.JobPositionRepository(uow);
704
705                #region JobPosition Creation
706
707                var jpIndex = 0;
708                PMS.Domain.Model.JobPositions.JobPosition jobPositionParent = null;
709                foreach (var pmsAdminJobPosition in jobPositionList)
710                {
711                    var jobPosition = new PMS.Domain.Model.JobPositions.JobPosition(period,
712                        new Domain.Model.JobPositions.SharedJobPosition(new Domain.Model.JobPositions.SharedJobPositionId(pmsAdminJobPosition.Id.Id), pmsAdminJobPosition.Name, pmsAdminJobPosition.DictionaryName)
713                        , jobPositionParent,
714                        jobInPeriodList[jpIndex],
715                        unitInPeriodList[jpIndex]
716                        );
717
718                    if (jpIndex != 1 && jpIndex != 2)
719                        jobPositionParent = jobPosition;
720
721                    jobPositionInPeriodList.Add(jobPosition);
722                    jobPositionRep.Add(jobPosition);
723                    jpIndex++;
724                }
725                #endregion
726
727                var employeeRep = new PMS.Persistence.NH.EmployeeRepository(uow);
728
729                #region Employee Creation
730
731                for (var i = 0; i < 10; i++)
732                {
733                    var employeeCustomFields =
734                        employeeCftList.ToList()
735                            .ToDictionary(
736                                e =>
737                                    new Domain.Model.Employees.SharedEmployeeCustomField(
738                                        new Domain.Model.Employees.SharedEmployeeCustomFieldId(e.Id.Id), e.Name,
739                                        e.DictionaryName, e.MinValue, e.MaxValue), e => e.Id.Id.ToString());
740                    var employee =
741                        new PMS.Domain.Model.Employees.Employee(
742                            ((i + 1) * 2000).ToString(), period, "کارمند" + i,
743                            "کارمندیان" + i, employeeCustomFields);
744
745
746
747                    var jobPositionInPeriod = jobPositionInPeriodList.Skip(i / 2).Take(1).Single();
748
749                    var jobcustomFields = jobInPeriodList.Single(j => j.Id.Equals(jobPositionInPeriod.JobId)).CustomFields;
750                    if (jobcustomFields != null && jobcustomFields.Count != 0)
751                    {
752                        var employeeJobPosition = new Domain.Model.Employees.EmployeeJobPosition(employee, jobPositionInPeriod, period.StartDate, period.EndDate, 100, 1,
753                        jobcustomFields.Select(j => new EmployeeJobCustomFieldValue(j.Id, "10")).ToList()
754                        );
755                        employee.AssignJobPositions(new List<Domain.Model.Employees.EmployeeJobPosition> { employeeJobPosition }, periodManagerService);
756
757                    }
758
759                    empList.Add(employee);
760                    employeeRep.Add(employee);
761
762                }
763                #endregion
764
765                uow.Commit();
766            }
767
768            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
769            {
770                var jobPositionRep = new PMS.Persistence.NH.JobPositionRepository(uow);
771                var jobRep = new PMS.Persistence.NH.JobRepository(uow);
772                var jobIndexRep = new PMS.Persistence.NH.JobIndexRepository(uow);
773                var inquiryRep = new InquiryJobIndexPointRepository(uow);
774                var inquiryConfiguratorService = new JobPositionInquiryConfiguratorService(jobPositionRep);
775
776                foreach (var jobPosition in jobPositionInPeriodList)
777                {
778                    var jobp = jobPositionRep.GetBy(jobPosition.Id);
779                    jobp.ConfigeInquirer(inquiryConfiguratorService, false);
780                }
781                uow.Commit();
782            }
783
784            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
785            {
786                var jobPositionRep = new PMS.Persistence.NH.JobPositionRepository(uow);
787                var jobRep = new PMS.Persistence.NH.JobRepository(uow);
788                var jobIndexRep = new PMS.Persistence.NH.JobIndexRepository(uow);
789                var inquiryRep = new InquiryJobIndexPointRepository(uow);
790                var inquiryConfiguratorService = new JobPositionInquiryConfiguratorService(jobPositionRep);
791
792                foreach (var jobPosition in jobPositionInPeriodList)
793                {
794                    var jobp = jobPositionRep.GetBy(jobPosition.Id);
795                    foreach (var itm in jobp.ConfigurationItemList)
796                    {
797                        var job = jobRep.GetById(itm.JobPosition.JobId);
798                        foreach (var jobIndexId in job.JobIndexList)
799                        {
800                            var jobIndex = jobIndexRep.GetById(jobIndexId.JobIndexId);
801                            if ((jobIndex as JobIndex).IsInquireable)
802                            {
803                                var id = inquiryRep.GetNextId();
804                                var inquiryIndexPoint = new Domain.Model.InquiryJobIndexPoints.InquiryJobIndexPoint(
805                                    new Domain.Model.InquiryJobIndexPoints.InquiryJobIndexPointId(id),
806                                    itm, jobIndex as Domain.Model.JobIndices.JobIndex, "5");
807                                inquiryRep.Add(inquiryIndexPoint);
808                            }
809
810                        }
811                    }
812                }
813                uow.Commit();
814            }
815
816            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
817            {
818                EventPublisher publisher = new EventPublisher();
819                var rebps = new RuleBasedPolicyEngineService(new LocatorProvider("PMSDb"), publisher);
820                var policyRep = new MITD.PMS.Persistence.NH.PolicyRepository(uow,
821                    new PolicyConfigurator(rebps));
822                var pmsPolicy = policyRep.GetById(new PolicyId(policy.Id.Id));
823
824                var calcRep = new CalculationRepository(uow);
825                var calc = new Calculation(calcRep.GetNextId(), period, pmsPolicy,
826                    "محاسبه آزمایشی", DateTime.Now, empList[0].Id.EmployeeNo + ";" + empList[1].Id.EmployeeNo);
827                calcRep.Add(calc);
828                uow.Commit();
829            }
830        }
831
832        [TestMethod]
833        public void CalculationTest()
834        {
835
836            MITD.PMSAdmin.Domain.Model.Policies.PolicyId policyId;
837            var empLst = string.Empty;
838            PMSAdmin.Domain.Model.JobIndices.JobIndex sharedji;
839
840            using (var transaction = new TransactionScope())
841            using (var puow = new NHUnitOfWork(PMSAdminSession.GetSession()))
842            using (var reuow = new NHUnitOfWork(RuleEngineSession.GetSession()))
843            {
844                var ruleRep = new RuleRepository(reuow);
845                var rfRep = new RuleFunctionRepository(reuow);
846                var reConfigRep = new REConfigeRepository(reuow);
847                var rebps = new RuleBasedPolicyEngineService(new LocatorProvider("PMSDb"), publisher);
848                var policyRep = new MITD.PMSAdmin.Persistence.NH.PolicyRepository(puow);
849
850                var rule = new Rule(new RuleId(ruleRep.GetNextId()), Guid.NewGuid().ToString(),
851@"
852	RuleExecutionUtil.Res.Add( new RuleResult{Value = data.Data});                            
853", RuleType.PerCalculation, 1);
854                ruleRep.Add(rule);
855
856                var policy = new MITD.PMSAdmin.Domain.Model.Policies.RuleEngineBasedPolicy(
857                    policyRep.GetNextId(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
858                policyId = policy.Id;
859                policyRep.Add(policy);
860                policy.AssignRule(rule);
861
862                var jirep = new PMSAdmin.Persistence.NH.JobIndexRepository(puow);
863                var ai = new PMSAdmin.Domain.Model.JobIndices.JobIndexCategory(
864                    jirep.GetNextId(), null,
865                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
866                jirep.Add(ai);
867
868                sharedji = new PMSAdmin.Domain.Model.JobIndices.JobIndex(
869                    jirep.GetNextId(), ai,
870                    Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
871                jirep.Add(sharedji);
872
873                reuow.Commit();
874                puow.Commit();
875                transaction.Complete();
876            }
877
878            Calculation calc;
879            var puows = new UnitOfWorkScope(new NHUnitOfWorkFactory(() => PMSAdminSession.GetSession()));
880            var uows = new UnitOfWorkScope(new NHUnitOfWorkFactory(() =>
881                {
882                    var res = PMSSession.GetSession();
883                    res.SetBatchSize(100);
884                    return res;
885                }));
886
887            Period period;
888            using (var transaction = new TransactionScope())
889            using (var puow = puows.CurrentUnitOfWork as NHUnitOfWork)
890            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
891            {
892                var periodRep = new PeriodRepository(uow);
893                period = new Period(new PeriodId(periodRep.GetNextId()), Guid.NewGuid().ToString(), DateTime.Now, DateTime.Now,91);
894                periodRep.Add(period);
895
896
897                var sjiService = new PMS.ACL.PMSAdmin.PMSAdminService(null, null, null, null,
898                    new PMSAdmin.Application.JobIndexService(new PMSAdmin.Persistence.NH.JobIndexRepository(puow),
899                        new PMSAdmin.Persistence.NH.CustomFieldRepository(puow))
900                         ,
901                            new PMSAdmin.Application.UnitIndexService(new PMSAdmin.Persistence.NH.UnitIndexRepository(uows),
902                            new PMSAdmin.Persistence.NH.CustomFieldRepository(uows)
903                    )
904                        );
905                var sji = sjiService.GetSharedJobIndex(new PMS.Domain.Model.JobIndices.SharedJobIndexId(sharedji.Id.Id));
906
907                var jiRep = new PMS.Persistence.NH.JobIndexRepository(uow);
908                var jic = new PMS.Domain.Model.JobIndices.JobIndexGroup(
909                    jiRep.GetNextId(), period, null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
910                jiRep.Add(jic);
911
912                var ji = new PMS.Domain.Model.JobIndices.JobIndex(
913                    jiRep.GetNextId(), period, sji, jic, true);
914                jiRep.Add(ji);
915                uow.Commit();
916                transaction.Complete();
917            }
918
919            for (int j = 0; j < 10; j++)
920            {
921                using (var transaction = new TransactionScope())
922                using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
923                {
924                    var empRep = new EmployeeRepository(uow);
925
926                    for (int i = 0; i < 500; i++)
927                    {
928                        var emp = new Employee(Guid.NewGuid().ToString(), period, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
929                        empLst += emp.Id.EmployeeNo + ";";
930                        empRep.Add(emp);
931                    }
932                    empLst = empLst.Remove(empLst.Length - 1);
933                    uow.Commit();
934                    transaction.Complete();
935                }
936            }
937
938            using (var transaction = new TransactionScope())
939            using (var uow = uows.CurrentUnitOfWork as NHUnitOfWork)
940            {
941                var rebps = new RuleBasedPolicyEngineService(new LocatorProvider("PMSDb"), publisher);
942                var calcRep = new CalculationRepository(uow);
943                var policyRep = new MITD.PMS.Persistence.NH.PolicyRepository(uow,
944                    new PolicyConfigurator(rebps));
945                var policy = policyRep.GetById(new PolicyId(policyId.Id));
946                calc = new Calculation(calcRep.GetNextId(), period, policy,
947                    Guid.NewGuid().ToString(), DateTime.Now, empLst);
948                calcRep.Add(calc);
949                uow.Commit();
950                transaction.Complete();
951            }
952
953            //var calculator = new JobIndexPointCalculator(publisher);
954
955            //using (var transaction = new TransactionScope())
956            //using (var uow = new NHUnitOfWork(PMSSession.GetSession()))
957            //{
958            //    var calcRep = new CalculationRepository(uow);
959            //    calc = calcRep.GetById(calc.Id);
960            //    calc.Run(calculator);
961            //    uow.Commit();
962            //    transaction.Complete();
963            //}
964
965            //var t = Task.Factory.StartNew(() =>
966            //    {
967            //        Thread.Sleep(1000);
968            //        using (var transaction = new TransactionScope())
969            //        using (var uow = new NHUnitOfWork(PMSSession.GetSession()))
970            //        {
971            //            var calcRep = new CalculationRepository(uow);
972            //            calc = calcRep.GetById(calc.Id);
973            //            calc.Stop(calculator);
974            //            uow.Commit();
975            //            transaction.Complete();
976            //        }
977            //    });
978            //t.Wait();
979        }
980
981    }
982}