public JsonResult Create(LeaveAbsenceViewModel data)
        {
            if (ModelState.IsValid)
            {
                using (var orgSession = OrgStore.OpenSession())
                {
                    var type = orgSession.Load<LeaveType>(data.LeaveTypeId);
                    var subject = orgSession.Load<User>(data.UserId);

                    var leave = new Leave
                                    {
                                        Subject = subject.ToSimpleUser(),
                                        LeaveType = type,
                                        StartOfProcess = data.StartOfProcess,
                                        EndOfProcess = data.EndOfProcess,
                                        ConsolidatedCompletionDate = data.EndOfProcess ?? DateTime.Now,
                                        Title = data.Title,
                                        Summary = data.Summary,
                                        UserCreatedProcess = OrgUser.ToSimpleUser(),
                                        Id = IlluminateDatabase.GenerateId<Leave>(),
                                        Approval = null,
                                        
                                    };


                    //If leave was created by a manager, then approve it already. 
                    if (subject.CanBeManagedBy((User)OrgUser)) //TODO: might be good to return the relationship that caused the approval.
                    {
                        leave.Approval = Approval.CreateApproval(OrgUser.ToSimpleUser());  
                    }

                    //get the workflow config
                    var config = orgSession.Query<LeaveWorkflowConfiguration>().FirstOrDefault();
                    if (config == null)
                    {
                        GetLogger().Error(string.Format("Cannot get sickness config for {0} organisation - no document in database, creating a default", OrgKey));
                        config = LeaveWorkflowConfiguration.GetDefault();
                        orgSession.Store(config);
                        orgSession.SaveChanges();
                    }

                    //create a new default leave workflow and assign to Leave - store it in the DB
                    leave.Workflow = new DefaultLeaveWorkflow(config);
                    orgSession.Store(leave);

                    //update the user state. 
                    if (leave.StartOfProcess.Date <= DateTime.Today && leave.ConsolidatedCompletionDate.Date >= DateTime.Today)
                    {
                        subject.CurrentState = "onleave";
                    }
                    //handle the create leave event
                    leave.HandleEvent(OrgStore, "Leave", "Create", leave);

                    orgSession.SaveChanges();

                    return JsonSuccess(leave.ToTimelineItems(), "Leave item created");
                }
            }

            return JsonError("Invalid data: " + ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1));
        }
        public override void Import(Stream stream)
        {

            ErrorLines.Clear();

            var reader = new StreamReader(stream);
            string line ;
            //ignore first line(s). 
            for (var i = 0; i < IgnoreLines; i++)
            {
                reader.ReadLine();
            }

            //parse each line
            var re =
                new Regex(
                    @"^(?<personnelnumber>[^\t]+)\t(?<startdate>[^\t]+)\t(?<enddate>[^\t]+)\t(?<leavetype>[^\t]+)\t(?<title>[^\t]*)$");
            //TODO: more sophisticated regex for dates etc. 
            

            while ((line = reader.ReadLine()) != null)
            {
                var match = re.Match(line);
                if (match.Success)
                {
                    using (var Session = Store.OpenSession())
                    {
                        //match relevant bits. 
                        var personnelnumber = match.Groups["personnelnumber"].Captures[0].Value;
                        var user = Session.Query<User>().FirstOrDefault(u => u.PersonnelNumber == personnelnumber);
                        if (user == null)
                        {
                            ErrorLines.Add(line);
                            continue;
                        }


                        var leavetype = match.Groups["leavetype"].Captures[0].Value;
                        var type = Session.Query<LeaveType>().FirstOrDefault(r => r.Code == leavetype);

                        if (type == null)
                        {
                            //get default reason
                            type =
                                Session.Query<LeaveType>().FirstOrDefault(r => r.Code == "DEFAULT");
                            if (type == null)
                            {
                                //!!
                                type = new LeaveType
                                           {
                                               Code = "DEFAULT",
                                               Name = "Default Leave Type"
                                           };
                                Session.Store(type);
                            }
                        }


                        var leave = new Leave
                                        {
                                            Id = IlluminateDatabase.GenerateId<Leave>(),
                                            StartOfProcess = DateTime.Parse(match.Groups["startdate"].Captures[0].Value),
                                            EndOfProcess = DateTime.Parse(match.Groups["enddate"].Captures[0].Value),
                                            ConsolidatedCompletionDate =
                                                DateTime.Parse(match.Groups["enddate"].Captures[0].Value),
                                            Subject = user.ToSimpleUser(),
                                            Title = match.Groups["title"].Captures[0].Value,
                                            Summary = match.Groups["title"].Captures[0].Value,
                                            LeaveType = type
                                        };

                        Session.Store(leave);

                        //should we save if there were errors?
                        Session.SaveChanges();
                    }
                }
                else
                {
                    ErrorLines.Add(line);
                }


                



            }


        }
        private Leave GenerateALeave(bool isCurrent, IUser user,Random rand)
        {

            var manager = user.Relationships.FirstOrDefault(r => r.RelationshipName == "LineManager");
            if (manager == null)
            {
                return null;
            }
            var leave = new Leave
            {
                CurrentProcessOwner = manager,
                Id = IlluminateDatabase.GenerateId<Leave>(),
                Title = "Annual Leave",
                Subject = user.ToSimpleUser(),
                UserCreatedProcess = manager,
                Summary = "Off to the coast!",
                LeaveType = _leaveType
            };
            
            var now = DateTime.UtcNow.Date;
            if (isCurrent)
            {
                leave.StartOfProcess = RandomDate(rand, now.AddDays(0 - _config.LeaveConfig.MaxDurationDays), now);
                leave.ConsolidatedCompletionDate = now;
            }
            else
            {
                var startDate = RandomDate(rand, now.AddDays(0 - _config.DaysHistory), now);
                var endDate = startDate.AddDays(rand.Next(1, _config.LeaveConfig.MaxDurationDays));
                if (endDate >= now)
                    endDate = now.AddDays(-1);
                leave.ConsolidatedCompletionDate = endDate;
                leave.EndOfProcess = endDate;
                leave.StartOfProcess = startDate;
            }
            leave.Approval = new Approval {ApprovalDate = leave.StartOfProcess.AddDays(-5), ApprovedBy = manager};
            return leave;
        }