Esempio n. 1
0
        private async Task createrole(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                var db       = services.GetService <ApplicationDbContext>();
                if (db.Database.GetPendingMigrations().Any())
                {
                    await db.Database.MigrateAsync();

                    var _rolemanager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();

                    if (!await _rolemanager.RoleExistsAsync("Admin"))
                    {
                        await _rolemanager.CreateAsync(new IdentityRole("Admin"));
                    }
                    if (!await _rolemanager.RoleExistsAsync("Student"))
                    {
                        await _rolemanager.CreateAsync(new IdentityRole("Student"));
                    }
                }
                // await ScheduleEmail(db);
                // await SendEm();
                ScheduleEmail send = new ScheduleEmail(db);
                send.getEvent();
            }
        }
Esempio n. 2
0
        public void when_email_is_scheduled_is_sent_when_is_due_repeatedly()
        {
            var settings = ReminderSettings.Default
                           .WithPersistenceId("email")
                           .WithTickInterval(TimeSpan.FromMilliseconds(500))
                           .WithSnapshotInterval(5);
            var taskId         = Guid.NewGuid().ToString();
            var probe          = CreateTestProbe("email-sender");
            var scheduler      = (TestScheduler)Sys.Scheduler;
            var emailScheduler = Sys.ActorOf(Props.Create(() => new EmailScheduler(settings)).WithDispatcher(CallingThreadDispatcher.Id), "email");
            var when           = DateTime.UtcNow.AddDays(1);
            var job            = new ScheduleEmail("me", "you", "hi");
            var ack            = new Ack(taskId);
            var schedule       = new Reminder.ScheduleRepeatedly(taskId, probe.Ref.Path, job, when, TimeSpan.FromHours(1), ack);

            emailScheduler.Tell(schedule, probe);
            probe.ExpectMsg <Ack>(x => x.Id == taskId);
            scheduler.AdvanceTo(when);

            probe.ExpectMsg <ScheduleEmail>(x => x.Body == job.Body && x.From == job.From && x.To == job.To);

            scheduler.Advance(TimeSpan.FromHours(1));

            probe.ExpectMsg <ScheduleEmail>(x => x.Body == job.Body && x.From == job.From && x.To == job.To);

            scheduler.Advance(TimeSpan.FromHours(1));

            probe.ExpectMsg <ScheduleEmail>(x => x.Body == job.Body && x.From == job.From && x.To == job.To);

            scheduler.Advance(TimeSpan.FromHours(1));

            probe.ExpectMsg <ScheduleEmail>(x => x.Body == job.Body && x.From == job.From && x.To == job.To);
        }
Esempio n. 3
0
        public void myTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
        {
            var listOfLowStockItems = CatalogueBizLogic.ListLowStockItems();

            ScheduleEmail objScheduleMail = new ScheduleEmail();

            objScheduleMail.SendScheduleMail(listOfLowStockItems);
        }
Esempio n. 4
0
        // [HttpPost]
        public async Task <IActionResult> ChooseEventB(EventModel model)
        {
            // var Event = from crs in db.Events where crs.EventId == model.EventId select crs;
            // EventModel crs = Event[0];


            var evt = db.Events.SingleOrDefault(e => e.EventId == model.EventId);

            if (evt.OccupiedSeats >= evt.NumberOfSeats)
            {
                TempData["Message"] = "The event is full!";
                // return View();
                return(RedirectToAction("ChooseEvent", "Event"));
            }
            evt.OccupiedSeats += 1;

            var us = await GetCurrentUserAsync();

            var check = db.StudentEvents.SingleOrDefault(l => l.EventId == model.EventId && l.ApplicationUser == us);

            if (check != null)
            {
                TempData["Message"] = "Duplicated Enrollment!";
                // return View("ChooseEvent");
                return(RedirectToAction("ChooseEvent", "Event"));
            }



            StudentEvent scs = new StudentEvent();

            scs.EventId         = model.EventId;
            scs.ApplicationUser = us;

            db.StudentEvents.Add(scs);



            db.SaveChanges();
            ScheduleEmail send = new ScheduleEmail(db);

            send.getEvent();


            // return PartialView("part",_model);
            return(RedirectToAction("ChooseEvent", "Event"));
            // return View(db.Events.ToList());
        }
Esempio n. 5
0
        public IActionResult GroupEvent(GEvent model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var GroupList = (from us in db.Users
                                 join sc in db.StudentCourses on us.Id equals sc.ApplicationUser.Id
                                 where sc.GroupNumber == model.GroupNumber && sc.CourseId == model.CourseId
                                 select us).ToList();


                EventModel EM = new EventModel {
                    Date          = model.Date,
                    Time          = model.Time,
                    Location      = model.Location,
                    NumberOfSeats = GroupList.Count,
                    OccupiedSeats = GroupList.Count,
                    Title         = model.Title,
                    Description   = model.Description
                };
                db.Events.Add(EM);

                foreach (var item in GroupList)
                {
                    StudentEvent scs = new StudentEvent();
                    scs.EventId         = EM.EventId;
                    scs.ApplicationUser = item;

                    db.StudentEvents.Add(scs);
                }



                db.SaveChanges();
                ScheduleEmail send = new ScheduleEmail(db);
                send.getEvent();
                TempData["Message"] = "Group created successfully!";
            }
            else
            {
                TempData["Message"] = "Group created failed!";
            }


            return(RedirectToAction("ChooseEvent", "Event"));
        }
Esempio n. 6
0
        static void AlertProbation(string connection, string database, string debug)
        {
            #region Connection, Setting & Filter
            MongoDBContext.ConnectionString = connection;
            MongoDBContext.DatabaseName     = database;
            MongoDBContext.IsSSL            = true;
            MongoDBContext dbContext = new MongoDBContext();
            var            url       = Constants.System.domain;
            var            now       = DateTime.Now;
            #endregion

            var listAlert = dbContext.Employees.Find(m => m.Enable.Equals(true) && m.Leave.Equals(false) && m.Official.Equals(false)).ToEnumerable()
                            .Where(m => m.ProbationAlert == 0).ToList();

            #region Tos
            var tos         = new List <EmailAddress>();
            var listHrRoles = dbContext.RoleUsers.Find(m => m.Role.Equals(Constants.Rights.HR) && (m.Expired.Equals(null) || m.Expired > DateTime.Now)).ToList();
            if (listHrRoles != null && listHrRoles.Count > 0)
            {
                foreach (var item in listHrRoles)
                {
                    if (item.Action == 3)
                    {
                        var fields = Builders <Employee> .Projection.Include(p => p.Email).Include(p => p.FullName);

                        var emailEntity = dbContext.Employees.Find(m => m.Id.Equals(item.User)).Project <Employee>(fields).FirstOrDefault();
                        if (emailEntity != null)
                        {
                            tos.Add(new EmailAddress {
                                Name = emailEntity.FullName, Address = emailEntity.Email
                            });
                        }
                    }
                }
            }
            #endregion

            if (listAlert.Count > 0)
            {
                foreach (var item in listAlert)
                {
                    if (item != null)
                    {
                        var typeEmail = "probation-alert";
                        var subject   = "[THỬ VIỆC] THÔNG BÁO ĐẾN HẠN XÉT LÀM VIỆC CHÍNH THỨC !!!";
                        var phone     = string.Empty;
                        if (item.Mobiles != null && item.Mobiles.Count > 0)
                        {
                            foreach (var mobile in item.Mobiles)
                            {
                                if (!string.IsNullOrEmpty(mobile.Number))
                                {
                                    phone += "<a href='tel:" + mobile.Number + "'>" + mobile.Number + "</a>";
                                }
                            }
                        }
                        var linkInformation = Constants.LinkHr.Main + "/" + Constants.LinkHr.Human + "/" + Constants.LinkHr.Information + "/" + item.Id;
                        var pathToFile      = @"C:\Projects\App.Schedule\Templates\ProbationAlert.html";
                        var bodyBuilder     = new BodyBuilder();
                        using (StreamReader SourceReader = File.OpenText(pathToFile))
                        {
                            bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                        }
                        string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                           subject,
                                                           item.FullName,
                                                           item.ChucVuName,
                                                           item.PhongBanName,
                                                           item.BoPhanName,
                                                           item.Joinday.ToString("dd/MM/yyyy"),
                                                           item.ProbationMonth,
                                                           phone,
                                                           item.Email,
                                                           url + "/" + linkInformation,
                                                           url);
                        var emailMessage = new EmailMessage()
                        {
                            ToAddresses = tos,
                            Subject     = subject,
                            BodyContent = messageBody,
                            Type        = typeEmail,
                            EmployeeId  = item.Id
                        };

                        var scheduleEmail = new ScheduleEmail
                        {
                            Status     = (int)EEmailStatus.Schedule,
                            To         = emailMessage.ToAddresses,
                            CC         = emailMessage.CCAddresses,
                            BCC        = emailMessage.BCCAddresses,
                            Type       = emailMessage.Type,
                            Title      = emailMessage.Subject,
                            Content    = emailMessage.BodyContent,
                            EmployeeId = emailMessage.EmployeeId
                        };
                        dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                    }
                }
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            #region Connection
            //var connectString = "mongodb://192.168.2.223:27017";
            var connection = ConfigurationSettings.AppSettings.Get("connection").ToString();
            var database   = ConfigurationSettings.AppSettings.Get("database").ToString();
            MongoDBContext.ConnectionString = connection;
            MongoDBContext.DatabaseName     = database;
            MongoDBContext.IsSSL            = true;
            MongoDBContext dbContext = new MongoDBContext();
            #endregion
            var now   = DateTime.Now;
            var url   = Constants.System.domain;
            var froms = new List <EmailAddress>
            {
                new EmailAddress {
                    Name    = Constants.System.emailHrName,
                    Address = Constants.System.emailHr,
                    Pwd     = Constants.System.emailHrPwd
                }
            };

            #region CCs

            #endregion
            var ccs         = new List <EmailAddress>();
            var listHrRoles = dbContext.RoleUsers.Find(m => m.Role.Equals(Constants.Rights.NhanSu) && (m.Expired.Equals(null) || m.Expired > DateTime.Now)).ToList();
            if (listHrRoles != null && listHrRoles.Count > 0)
            {
                foreach (var item in listHrRoles)
                {
                    if (item.Action == 3)
                    {
                        var fields = Builders <Employee> .Projection.Include(p => p.Email).Include(p => p.FullName);

                        var emailEntity = dbContext.Employees.Find(m => m.Id.Equals(item.User)).Project <Employee>(fields).FirstOrDefault();
                        if (emailEntity != null)
                        {
                            ccs.Add(new EmailAddress {
                                Name = emailEntity.FullName, Address = emailEntity.Email
                            });
                        }
                    }
                }
            }

            var birthdays = dbContext.Employees.Find(m => m.Enable.Equals(true) && m.Leave.Equals(false) && m.Birthday > Constants.MinDate).ToEnumerable()
                            .Where(m => m.RemainingBirthDays == 0).ToList();

            if (birthdays.Count > 0)
            {
                foreach (var item in birthdays)
                {
                    if (item != null && !string.IsNullOrEmpty(item.Email))
                    {
                        Console.WriteLine(item.Email);
                        var subject = "CHÚC MỪNG SINH NHẬT !!!";
                        var title   = string.Empty;
                        if (!string.IsNullOrEmpty(item.Gender))
                        {
                            title = item.Gender == "Nam" ? "anh" : "chị";
                            if (item.AgeBirthday > 50)
                            {
                                title = item.Gender == "Nam" ? "ông" : "bà";
                            }
                        }
                        var fullName = item.FullName;
                        var tos      = new List <EmailAddress>
                        {
                            new EmailAddress {
                                Name = item.FullName, Address = item.Email
                            }
                        };
                        //C:\Projects\App.Schedule\BirthdaySchedule\Templates
                        var pathToFile = @"C:\Projects\App.Schedule\Templates\HappyBirthday.html";
                        // Must be fullpath. because task schedule un known path.
                        // var pathToFile = @"C:\Projects\Tribat\sourcecode\xbirthday\bin\Debug\Templates\HappyBirthday.html";
                        var bodyBuilder = new BodyBuilder();
                        using (StreamReader SourceReader = File.OpenText(pathToFile))
                        {
                            bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                        }
                        string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                           subject,
                                                           title,
                                                           fullName,
                                                           url);
                        var emailMessage = new EmailMessage()
                        {
                            FromAddresses = froms,
                            ToAddresses   = tos,
                            CCAddresses   = ccs,
                            Subject       = subject,
                            BodyContent   = messageBody,
                            Type          = "birthday",
                            EmployeeId    = item.EmployeeId
                        };

                        // For faster update.
                        var scheduleEmail = new ScheduleEmail
                        {
                            Status     = (int)EEmailStatus.Schedule,
                            To         = emailMessage.ToAddresses,
                            CC         = emailMessage.CCAddresses,
                            BCC        = emailMessage.BCCAddresses,
                            Type       = emailMessage.Type,
                            Title      = emailMessage.Subject,
                            Content    = emailMessage.BodyContent,
                            EmployeeId = emailMessage.EmployeeId
                        };
                        dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                        //new AuthMessageSender().SendEmail(emailMessage);
                    }
                }
            }
        }
Esempio n. 8
0
        public IActionResult TangCaNhanVien(int code, int approve, string secure)
        {
            var viewModel = new TimeKeeperViewModel
            {
                Approve = approve
            };

            #region Extensions
            var builderTraining = Builders <Trainning> .Filter;
            var filterTraining  = builderTraining.Eq(m => m.Enable, true);
            filterTraining = filterTraining & builderTraining.Eq(m => m.Type, "anh-van");
            var listTraining = dbContext.Trainnings.Find(filterTraining).Limit(10).SortByDescending(m => m.CreatedOn).ToList();
            viewModel.ListTraining = listTraining;
            #endregion

            var list = dbContext.OvertimeEmployees.Find(m => m.Code.Equals(code) && m.Secure.Equals(secure)).ToList();

            if (list != null && list.Count > 0)
            {
                var filter = Builders <OvertimeEmployee> .Filter.Eq(m => m.CodeInt, code) & Builders <OvertimeEmployee> .Filter.Eq(m => m.Secure, secure);

                var update = Builders <OvertimeEmployee> .Update
                             .Set(m => m.Secure, DateTime.Now.ToString("yyyyMMddHHmmssfff"))
                             .Set(m => m.Status, approve)
                             .Set(m => m.ApprovedOn, DateTime.Now);

                dbContext.OvertimeEmployees.UpdateMany(filter, update);

                #region Send mail AN NINH
                if (approve == (int)EOvertime.Ok)
                {
                    #region parameters
                    //{0} : Subject
                    //{1} : Gender Nguoi nhan
                    //{2} : Fullname nguoi nhan
                    //{3} : Gender nguoi yeu cau
                    //{4} : Fullname nguoi yeu cau
                    //{5} : Chức vụ
                    //{6} : Email
                    //{7} : Phone
                    //{8} : Noi dung . Example: bang tang ca ngày dd/MM/yyyy
                    //{9}: Link chi tiet
                    //{10}: Website
                    #endregion

                    var overtime = list.First();
                    var date     = overtime.Date;

                    var directorE = dbContext.Employees.Find(m => m.Id.Equals(overtime.ApprovedBy)).FirstOrDefault();

                    var securityPosition = dbContext.ChucVus.Find(m => m.Code.Equals("CHUCVU86")).FirstOrDefault();

                    var securityE = dbContext.Employees.Find(m => m.Enable.Equals(true) && m.Leave.Equals(false) && m.ChucVu.Equals(securityPosition.Id)).FirstOrDefault();

                    var genderDE      = directorE.Gender == "Nam" ? "Anh" : "Chị";
                    var genderDELower = directorE.Gender == "Nam" ? "anh" : "chị";
                    var genderSE      = securityE.Gender == "Nam" ? "anh" : "chị";

                    var phone = string.Empty;
                    if (directorE.Mobiles != null && directorE.Mobiles.Count > 0)
                    {
                        phone = directorE.Mobiles[0].Number;
                    }

                    var webRoot    = Environment.CurrentDirectory;
                    var pathToFile = _env.WebRootPath
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "Templates"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "EmailTemplate"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "OvertimeSecurity.html";

                    var tos = new List <EmailAddress>
                    {
                        new EmailAddress {
                            Name = securityE.FullName, Address = securityE.Email
                        }
                    };

                    var subject = "Kiểm tra Bảng tăng ca ngày " + date.ToString("dd/MM/yyyy");
                    var title   = "Bảng tăng ca ngày " + date.ToString("dd/MM/yyyy");

                    var linkDetail = Constants.System.domain + "/" + Constants.LinkTimeKeeper.Main + "/" + Constants.LinkTimeKeeper.Overtime + "?Tu=" + date.ToString("MM-dd-yyyy") + "&Den=" + date.ToString("MM-dd-yyyy");

                    var bodyBuilder = new BodyBuilder();
                    using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                    {
                        bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                    }
                    string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                       subject,
                                                       genderSE,
                                                       securityE.FullName,
                                                       genderDE,
                                                       directorE.FullName,
                                                       directorE.ChucVuName,
                                                       genderDELower,
                                                       directorE.Email,
                                                       phone,
                                                       title,
                                                       linkDetail,
                                                       Constants.System.domain
                                                       );

                    var emailMessage = new EmailMessage()
                    {
                        ToAddresses = tos,
                        Subject     = subject,
                        BodyContent = messageBody,
                        Type        = "overtime-security",
                        EmployeeId  = overtime.Code.ToString()
                    };

                    var scheduleEmail = new ScheduleEmail
                    {
                        Status     = (int)EEmailStatus.Schedule,
                        To         = emailMessage.ToAddresses,
                        CC         = emailMessage.CCAddresses,
                        BCC        = emailMessage.BCCAddresses,
                        Type       = emailMessage.Type,
                        Title      = emailMessage.Subject,
                        Content    = emailMessage.BodyContent,
                        EmployeeId = emailMessage.EmployeeId
                    };

                    dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                }
                #endregion

                ViewData["Status"] = "Cám ơn đã xác nhận, kết quả đang gửi cho người liên quan.";
                return(View(viewModel));
            }

            ViewData["Status"] = Constants.ErrorParameter;
            viewModel.Error    = true;
            return(View(viewModel));
        }
Esempio n. 9
0
        public IActionResult Phep(string id, int approve, string secure)
        {
            var viewModel = new LeaveViewModel
            {
                Approve = approve
            };
            var leave = dbContext.Leaves.Find(m => m.Id.Equals(id)).FirstOrDefault();

            #region Extensions: Trainning
            var builderTraining = Builders <Trainning> .Filter;
            var filterTraining  = builderTraining.Eq(m => m.Enable, true);
            filterTraining &= builderTraining.Eq(m => m.Type, "anh-van");
            var listTraining = dbContext.Trainnings.Find(filterTraining).Limit(10).SortByDescending(m => m.CreatedOn).ToList();
            viewModel.ListTraining = listTraining;
            #endregion

            if (leave == null || (leave.SecureCode != secure && leave.Status != 0))
            {
                ViewData["Status"] = Constants.ErrorParameter;
                viewModel.Error    = true;
                return(View(viewModel));
            }

            viewModel.Leave = leave;

            #region Update status
            var filter = Builders <Leave> .Filter.Eq(m => m.Id, id);

            var update = Builders <Leave> .Update
                         .Set(m => m.SecureCode, Helper.HashedPassword(Guid.NewGuid().ToString("N").Substring(0, 12)))
                         .Set(m => m.Status, approve)
                         .Set(m => m.ApprovedBy, leave.ApproverId);

            dbContext.Leaves.UpdateOne(filter, update);
            #endregion

            #region update Leave Date if CANCEL
            if (approve == 2)
            {
                #region QUAN LY LOAI PHEP, BU, NGHI KO TINH LUONG,...
                var typeLeave = dbContext.LeaveTypes.Find(m => m.Id.Equals(leave.TypeId)).FirstOrDefault();
                // Nghi phep
                if (typeLeave.Alias == "phep-nam")
                {
                    var builderLeaveEmployee = Builders <LeaveEmployee> .Filter;
                    var filterLeaveEmployee  = builderLeaveEmployee.Eq(m => m.EmployeeId, leave.EmployeeId)
                                               & builderLeaveEmployee.Eq(x => x.LeaveTypeId, leave.TypeId);
                    var updateLeaveEmployee = Builders <LeaveEmployee> .Update.Inc(m => m.Number, leave.Number);

                    dbContext.LeaveEmployees.UpdateOne(filterLeaveEmployee, updateLeaveEmployee);
                }
                // Phep khac,...
                #endregion
            }
            #endregion

            #region Send email to user leave, cc: người duyệt
            var approvement = dbContext.Employees.Find(m => m.Id.Equals(leave.ApproverId)).FirstOrDefault();
            // Tự yêu cầu
            bool seftFlag   = leave.EmployeeId == leave.CreatedBy ? true : false;
            var  employee   = dbContext.Employees.Find(m => m.Id.Equals(leave.EmployeeId)).FirstOrDefault();
            var  userCreate = employee;
            if (!seftFlag)
            {
                userCreate = dbContext.Employees.Find(m => m.Id.Equals(leave.CreatedBy)).FirstOrDefault();
            }
            var requester = employee.FullName;
            var tos       = new List <EmailAddress>
            {
                new EmailAddress {
                    Name = employee.FullName, Address = employee.Email
                }
            };
            if (approve == (int)EStatusLeave.Accept)
            {
                var hrs = Utility.EmailGet(Constants.Rights.NhanSu, (int)ERights.Edit);
                if (hrs != null && hrs.Count > 0)
                {
                    requester += " , HR";
                    foreach (var item in hrs)
                    {
                        if (tos.Count(m => m.Address.Equals(item.Address)) == 0)
                        {
                            tos.Add(item);
                        }
                    }
                }
            }

            // cc người tạo dùm
            var ccs = new List <EmailAddress>();
            if (!seftFlag)
            {
                ccs.Add(new EmailAddress {
                    Name = userCreate.FullName, Address = userCreate.Email
                });
            }
            // cc người duyệt
            ccs.Add(new EmailAddress {
                Name = approvement.FullName, Address = approvement.Email
            });

            var webRoot    = Environment.CurrentDirectory;
            var pathToFile = _env.WebRootPath
                             + Path.DirectorySeparatorChar.ToString()
                             + "Templates"
                             + Path.DirectorySeparatorChar.ToString()
                             + "EmailTemplate"
                             + Path.DirectorySeparatorChar.ToString()
                             + "LeaveApprove.html";

            var status      = approve == 1 ? "Đồng ý" : "Không đồng ý";
            var dateRequest = leave.From.ToString("dd/MM/yyyy HH:mm") + " - " + leave.To.ToString("dd/MM/yyyy HH:mm");

            var subject = "[Nghỉ phép] Kết quả duyệt: " + status + " - ngày " + dateRequest;

            var countLeaveDay = " (" + leave.Number + " ngày)";

            var linkDetail  = Constants.System.domain + "/" + Constants.LinkLeave.Main + "/" + Constants.LinkLeave.Index;
            var bodyBuilder = new BodyBuilder();
            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
            }
            string messageBody = string.Format(bodyBuilder.HtmlBody,
                                               subject,
                                               requester,
                                               status,
                                               approvement.FullName,
                                               approvement.Email,
                                               approvement.ChucVuName,
                                               dateRequest + countLeaveDay,
                                               leave.Reason,
                                               leave.TypeName,
                                               leave.Phone,
                                               linkDetail,
                                               Constants.System.domain
                                               );

            var emailMessage = new EmailMessage()
            {
                ToAddresses = tos,
                CCAddresses = ccs,
                Subject     = subject,
                BodyContent = messageBody,
                Type        = "leave-confirm",
                EmployeeId  = leave.EmployeeId
            };

            // For faster. Add to schedule.
            // Send later
            var scheduleEmail = new ScheduleEmail
            {
                Status = (int)EEmailStatus.Schedule,
                //From = emailMessage.FromAddresses,
                To         = emailMessage.ToAddresses,
                CC         = emailMessage.CCAddresses,
                BCC        = emailMessage.BCCAddresses,
                Type       = emailMessage.Type,
                Title      = emailMessage.Subject,
                Content    = emailMessage.BodyContent,
                EmployeeId = emailMessage.EmployeeId
            };
            dbContext.ScheduleEmails.InsertOne(scheduleEmail);
            //_emailSender.SendEmail(emailMessage);

            #endregion

            ViewData["Status"] = "Cám ơn đã xác nhận, kết quả đang gửi cho người liên quan.";

            return(View(viewModel));
        }
Esempio n. 10
0
        public IActionResult Cong(string id, int approve, string secure)
        {
            var viewModel = new TimeKeeperViewModel
            {
                Approve = approve
            };

            #region Extensions: Trainning
            var builderTraining = Builders <Trainning> .Filter;
            var filterTraining  = builderTraining.Eq(m => m.Enable, true);
            filterTraining &= builderTraining.Eq(m => m.Type, "anh-van");
            var listTraining = dbContext.Trainnings.Find(filterTraining).Limit(10).SortByDescending(m => m.CreatedOn).ToList();
            viewModel.ListTraining = listTraining;
            #endregion

            var timelog = dbContext.EmployeeWorkTimeLogs.Find(m => m.Id.Equals(id)).FirstOrDefault();
            if (timelog == null || (timelog.SecureCode != secure && timelog.Status != 2))
            {
                ViewData["Status"] = Constants.ErrorParameter;
                viewModel.Error    = true;
                return(View(viewModel));
            }

            viewModel.EmployeeWorkTimeLog = timelog;

            #region Update status
            var filter = Builders <EmployeeWorkTimeLog> .Filter.Eq(m => m.Id, id);

            var update = Builders <EmployeeWorkTimeLog> .Update
                         .Set(m => m.SecureCode, Helper.HashedPassword(Guid.NewGuid().ToString("N").Substring(0, 12)))
                         .Set(m => m.WorkDay, 1)
                         .Set(m => m.Status, approve)
                         .Set(m => m.ConfirmDate, DateTime.Now.Date);

            dbContext.EmployeeWorkTimeLogs.UpdateOne(filter, update);
            #endregion

            #region update Summary
            if (approve == (int)EStatusWork.DongY)
            {
                var monthDate        = Utility.EndWorkingMonthByDate(timelog.Date);
                var builderUpdateSum = Builders <EmployeeWorkTimeMonthLog> .Filter;
                var filterUpdateSum  = builderUpdateSum.Eq(m => m.EmployeeId, timelog.EmployeeId);
                filterUpdateSum &= builderUpdateSum.Eq(m => m.Year, monthDate.Year);
                filterUpdateSum &= builderUpdateSum.Eq(m => m.Month, monthDate.Month);

                double dateInc     = 0;
                double worktimeInc = 0;
                double lateInc     = 0;
                double earlyInc    = 0;
                if (!timelog.In.HasValue && !timelog.Out.HasValue)
                {
                    dateInc     += 1;
                    worktimeInc += new TimeSpan(8, 0, 0).TotalMilliseconds;
                }
                else if (!timelog.In.HasValue || !timelog.Out.HasValue)
                {
                    dateInc     += 0.5;
                    worktimeInc += new TimeSpan(4, 0, 0).TotalMilliseconds;
                }
                if (timelog.Late.TotalMilliseconds > 0)
                {
                    worktimeInc += timelog.Late.TotalMilliseconds;
                    lateInc     += timelog.Late.TotalMilliseconds;
                }
                if (timelog.Early.TotalMilliseconds > 0)
                {
                    worktimeInc += timelog.Early.TotalMilliseconds;
                    earlyInc    += timelog.Early.TotalMilliseconds;
                }
                var updateSum = Builders <EmployeeWorkTimeMonthLog> .Update
                                .Inc(m => m.Workday, dateInc)
                                .Inc(m => m.WorkTime, worktimeInc)
                                .Inc(m => m.Late, -(lateInc))
                                .Inc(m => m.Early, -(earlyInc))
                                .Set(m => m.LastUpdated, DateTime.Now);

                dbContext.EmployeeWorkTimeMonthLogs.UpdateOne(filterUpdateSum, updateSum);
            }
            #endregion

            #region Send email to user
            var approvement = dbContext.Employees.Find(m => m.Id.Equals(timelog.ConfirmId)).FirstOrDefault();
            var employee    = dbContext.Employees.Find(m => m.Id.Equals(timelog.EmployeeId)).FirstOrDefault();
            var requester   = employee.FullName;
            var tos         = new List <EmailAddress>
            {
                new EmailAddress {
                    Name = employee.FullName, Address = employee.Email
                }
            };
            if (approve == (int)EStatusWork.DongY)
            {
                var hrs = Utility.EmailGet(Constants.Rights.NhanSu, (int)ERights.Edit);
                if (hrs != null && hrs.Count > 0)
                {
                    requester += " , HR";
                    foreach (var item in hrs)
                    {
                        if (tos.Count(m => m.Address.Equals(item.Address)) == 0)
                        {
                            tos.Add(item);
                        }
                    }
                }
            }

            var ccs = new List <EmailAddress>();

            var webRoot    = Environment.CurrentDirectory;
            var pathToFile = _env.WebRootPath
                             + Path.DirectorySeparatorChar.ToString()
                             + "Templates"
                             + Path.DirectorySeparatorChar.ToString()
                             + "EmailTemplate"
                             + Path.DirectorySeparatorChar.ToString()
                             + "TimeKeeperConfirm.html";

            var subject   = "Xác nhận công.";
            var status    = approve == 3 ? "Đồng ý" : "Không duyệt";
            var inTime    = timelog.In.HasValue ? timelog.In.Value.ToString(@"hh\:mm") : string.Empty;
            var outTime   = timelog.Out.HasValue ? timelog.Out.Value.ToString(@"hh\:mm") : string.Empty;
            var lateTime  = timelog.Late.TotalMilliseconds > 0 ? Math.Round(timelog.Late.TotalMinutes, 0).ToString() : "0";
            var earlyTime = timelog.Early.TotalMilliseconds > 0 ? Math.Round(timelog.Early.TotalMinutes, 0).ToString() : "0";
            var sumTime   = string.Empty;
            if (string.IsNullOrEmpty(inTime) && string.IsNullOrEmpty(outTime))
            {
                sumTime = "1 ngày";
            }
            else if (string.IsNullOrEmpty(inTime) || string.IsNullOrEmpty(outTime))
            {
                sumTime = "0.5 ngày";
            }
            var minutesMissing = TimeSpan.FromMilliseconds(timelog.Late.TotalMilliseconds + timelog.Early.TotalMilliseconds).TotalMinutes;
            if (minutesMissing > 0)
            {
                if (!string.IsNullOrEmpty(sumTime))
                {
                    sumTime += ", ";
                }
                sumTime += Math.Round(minutesMissing, 0) + " phút";
            }

            var detailTimeKeeping = "Ngày: " + timelog.Date.ToString("dd/MM/yyyy") + "; thiếu: " + sumTime;
            if (!string.IsNullOrEmpty(inTime))
            {
                detailTimeKeeping += " | giờ vào: " + inTime + "; trễ: " + lateTime;
            }
            else
            {
                detailTimeKeeping += " | giờ vào: --; trễ: --";
            }
            if (!string.IsNullOrEmpty(outTime))
            {
                detailTimeKeeping += "; giờ ra: " + outTime + "; sớm: " + earlyTime;
            }
            else
            {
                detailTimeKeeping += "; giờ ra: --; sớm: --";
            }
            // Api update, generate code.
            var linkDetail  = Constants.System.domain;
            var bodyBuilder = new BodyBuilder();
            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
            }
            string messageBody = string.Format(bodyBuilder.HtmlBody,
                                               subject,
                                               requester,
                                               status,
                                               approvement.FullName,
                                               approvement.Email,
                                               approvement.ChucVuName,
                                               detailTimeKeeping,
                                               timelog.Reason,
                                               timelog.ReasonDetail,
                                               linkDetail,
                                               Constants.System.domain
                                               );

            var emailMessage = new EmailMessage()
            {
                ToAddresses = tos,
                CCAddresses = ccs,
                Subject     = subject,
                BodyContent = messageBody,
                Type        = "xac-nhan-cong",
                EmployeeId  = timelog.EmployeeId
            };

            var scheduleEmail = new ScheduleEmail
            {
                Status     = (int)EEmailStatus.Schedule,
                To         = emailMessage.ToAddresses,
                CC         = emailMessage.CCAddresses,
                BCC        = emailMessage.BCCAddresses,
                Type       = emailMessage.Type,
                Title      = emailMessage.Subject,
                Content    = emailMessage.BodyContent,
                EmployeeId = emailMessage.EmployeeId
            };
            dbContext.ScheduleEmails.InsertOne(scheduleEmail);
            #endregion

            ViewData["Status"] = "Cám ơn đã xác nhận, kết quả đang gửi cho người liên quan.";

            return(View(viewModel));
        }
Esempio n. 11
0
        /// <summary>
        /// Mailkit NOT WORKING ON 08.03.2019
        /// </summary>
        /// <param name="emailMessage"></param>
        public void SendEmailWithMailKit(EmailMessage emailMessage)
        {
            var message = new MimeMessage
            {
                Subject = emailMessage.Subject,
                Body    = new TextPart(TextFormat.Html)
                {
                    Text = emailMessage.BodyContent
                }
            };

            // Sometime null from, set default
            if (emailMessage.FromAddresses == null || emailMessage.FromAddresses.Count == 0)
            {
                emailMessage.FromAddresses = new List <EmailAddress>
                {
                    new EmailAddress {
                        Name = Constants.System.emailHrName, Address = Constants.System.emailHr, Pwd = Constants.System.emailHrPwd
                    }
                };
            }
            message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));

            // Check toemail
            var newToList = new List <EmailAddress>();

            if (emailMessage.ToAddresses != null && emailMessage.ToAddresses.Count > 0)
            {
                foreach (var item in emailMessage.ToAddresses)
                {
                    if (Utility.IsValidEmail(item.Address))
                    {
                        newToList.Add(item);
                    }
                    else
                    {
                        // Chỉ gửi cho email sai
                        var toError = new List <EmailAddress>
                        {
                            item
                        };
                        var errorEmail = new ScheduleEmail
                        {
                            From       = emailMessage.FromAddresses,
                            To         = toError,
                            CC         = emailMessage.CCAddresses,
                            BCC        = emailMessage.BCCAddresses,
                            Type       = emailMessage.Type,
                            Title      = emailMessage.Subject,
                            Content    = emailMessage.BodyContent,
                            Status     = (int)EEmailStatus.Fail,
                            Error      = "Sai định dạng mail",
                            ErrorCount = 0
                        };
                        _dbContext.ScheduleEmails.InsertOne(errorEmail);
                        SendMailSupport(errorEmail.Id);
                    }
                }
            }
            if (newToList != null && newToList.Count > 0)
            {
                message.To.AddRange(newToList.Select(x => new MailboxAddress(x.Name, x.Address)));

                if (emailMessage.CCAddresses != null && emailMessage.CCAddresses.Count > 0)
                {
                    message.Cc.AddRange(emailMessage.CCAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }
                if (emailMessage.BCCAddresses != null && emailMessage.BCCAddresses.Count > 0)
                {
                    message.Bcc.AddRange(emailMessage.BCCAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }

                #region Add to schedule
                var scheduleEmail = new ScheduleEmail
                {
                    From       = emailMessage.FromAddresses,
                    To         = emailMessage.ToAddresses,
                    CC         = emailMessage.CCAddresses,
                    BCC        = emailMessage.BCCAddresses,
                    Type       = emailMessage.Type,
                    Title      = message.Subject,
                    Content    = emailMessage.BodyContent,
                    EmployeeId = emailMessage.EmployeeId
                };
                _dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                #endregion
                var isEmailSent = (int)EEmailStatus.Send;
                var error       = string.Empty;
                try
                {
                    using (var emailClient = new MailKit.Net.Smtp.SmtpClient())
                    {
                        //The last parameter here is to use SSL (Which you should!)
                        emailClient.Connect(emailMessage.FromAddresses.First().Address, 465, true);

                        //Remove any OAuth functionality as we won't be using it.
                        emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                        emailClient.Authenticate(emailMessage.FromAddresses.First().Address, emailMessage.FromAddresses.First().Pwd);

                        emailClient.Send(message);
                        isEmailSent = (int)EEmailStatus.Ok;

                        emailClient.Disconnect(true);
                        #region Update status
                        var filter = Builders <ScheduleEmail> .Filter.Eq(m => m.Id, scheduleEmail.Id);

                        var update = Builders <ScheduleEmail> .Update
                                     .Set(m => m.Status, isEmailSent)
                                     .Set(m => m.UpdatedOn, DateTime.Now);

                        _dbContext.ScheduleEmails.UpdateOne(filter, update);
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    isEmailSent = (int)EEmailStatus.Fail;
                    error       = ex.Message;
                    #region Update status
                    var filter = Builders <ScheduleEmail> .Filter.Eq(m => m.Id, scheduleEmail.Id);

                    var update = Builders <ScheduleEmail> .Update
                                 .Set(m => m.Status, isEmailSent)
                                 .Set(m => m.Error, error)
                                 .Inc(m => m.ErrorCount, 1)
                                 .Set(m => m.UpdatedOn, DateTime.Now);

                    _dbContext.ScheduleEmails.UpdateOne(filter, update);
                    #endregion
                    SendMailSupport(scheduleEmail.Id);
                }
            }
        }
Esempio n. 12
0
        public void SendEmail(EmailMessage emailMessage)
        {
            MailMessage mail = new MailMessage
            {
                From = new MailAddress(_emailApp, _emailAppShow)
            };

            var newToList = new List <EmailAddress>();

            if (emailMessage.ToAddresses != null && emailMessage.ToAddresses.Count > 0)
            {
                foreach (var item in emailMessage.ToAddresses)
                {
                    if (Utility.IsValidEmail(item.Address))
                    {
                        newToList.Add(item);
                    }
                    else
                    {
                        var toError = new List <EmailAddress>
                        {
                            item
                        };
                        var errorEmail = new ScheduleEmail
                        {
                            From       = emailMessage.FromAddresses,
                            To         = toError,
                            CC         = emailMessage.CCAddresses,
                            BCC        = emailMessage.BCCAddresses,
                            Type       = emailMessage.Type,
                            Title      = emailMessage.Subject,
                            Content    = emailMessage.BodyContent,
                            Status     = (int)EEmailStatus.Fail,
                            Error      = "Sai định dạng mail",
                            ErrorCount = 0,
                            EmployeeId = emailMessage.EmployeeId
                        };
                        _dbContext.ScheduleEmails.InsertOne(errorEmail);
                        SendMailSupport(errorEmail.Id);
                    }
                }
            }

            if (newToList != null && newToList.Count > 0)
            {
                foreach (var to in emailMessage.ToAddresses)
                {
                    mail.To.Add(new MailAddress(to.Address, to.Name));
                }

                if (emailMessage.CCAddresses != null && emailMessage.CCAddresses.Count > 0)
                {
                    foreach (var cc in emailMessage.CCAddresses)
                    {
                        mail.CC.Add(new MailAddress(cc.Address, cc.Name));
                    }
                }

                if (emailMessage.BCCAddresses != null && emailMessage.BCCAddresses.Count > 0)
                {
                    foreach (var bcc in emailMessage.BCCAddresses)
                    {
                        mail.Bcc.Add(new MailAddress(bcc.Address, bcc.Name));
                    }
                }

                #region Add to schedule
                var scheduleEmail = new ScheduleEmail
                {
                    From       = emailMessage.FromAddresses,
                    To         = emailMessage.ToAddresses,
                    CC         = emailMessage.CCAddresses,
                    BCC        = emailMessage.BCCAddresses,
                    Type       = emailMessage.Type,
                    Title      = emailMessage.Subject,
                    Content    = emailMessage.BodyContent,
                    EmployeeId = emailMessage.EmployeeId
                };
                _dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                #endregion

                var isEmailSent = (int)EEmailStatus.Send;
                var error       = string.Empty;
                try
                {
                    var client = new System.Net.Mail.SmtpClient(_emailServer)
                    {
                        Port = 587, //465 timeout
                        UseDefaultCredentials = true,
                        Credentials           = new NetworkCredential(_emailApp, _emailAppPwd)
                    };

                    mail.Subject      = emailMessage.Subject;
                    mail.IsBodyHtml   = true;
                    mail.BodyEncoding = Encoding.UTF8;
                    mail.Body         = emailMessage.BodyContent;
                    client.Send(mail);

                    #region Update status
                    var filter = Builders <ScheduleEmail> .Filter.Eq(m => m.Id, scheduleEmail.Id);

                    var update = Builders <ScheduleEmail> .Update
                                 .Set(m => m.Status, isEmailSent)
                                 .Set(m => m.UpdatedOn, DateTime.Now);

                    _dbContext.ScheduleEmails.UpdateOne(filter, update);
                    #endregion
                }
                catch (Exception ex)
                {
                    isEmailSent = (int)EEmailStatus.Fail;
                    error       = ex.Message;
                    #region Update status
                    var filter = Builders <ScheduleEmail> .Filter.Eq(m => m.Id, scheduleEmail.Id);

                    var update = Builders <ScheduleEmail> .Update
                                 .Set(m => m.Status, isEmailSent)
                                 .Set(m => m.Error, error)
                                 .Inc(m => m.ErrorCount, 1)
                                 .Set(m => m.UpdatedOn, DateTime.Now);

                    _dbContext.ScheduleEmails.UpdateOne(filter, update);
                    #endregion
                    SendMailSupport(scheduleEmail.Id);
                }
            }
        }
Esempio n. 13
0
        static void SendMailBHXH(string connection, string database, int month)
        {
            #region Connection, Setting & Filter
            MongoDBContext.ConnectionString = connection;
            MongoDBContext.DatabaseName     = database;
            MongoDBContext.IsSSL            = true;
            MongoDBContext dbContext = new MongoDBContext();
            var            url       = Constants.System.domain;
            var            now       = DateTime.Now;
            #endregion

            var froms = new List <EmailAddress>
            {
                new EmailAddress {
                    Name    = Constants.System.emailHrName,
                    Address = Constants.System.emailHr,
                    Pwd     = Constants.System.emailHrPwd
                }
            };

            #region Tos
            var tos         = new List <EmailAddress>();
            var listHrRoles = dbContext.RoleUsers.Find(m => m.Role.Equals(Constants.Rights.NhanSu) && (m.Expired.Equals(null) || m.Expired > DateTime.Now)).ToList();
            if (listHrRoles != null && listHrRoles.Count > 0)
            {
                foreach (var item in listHrRoles)
                {
                    if (item.Action == 3)
                    {
                        var fields = Builders <Employee> .Projection.Include(p => p.Email).Include(p => p.FullName);

                        var emailEntity = dbContext.Employees.Find(m => m.Id.Equals(item.User)).Project <Employee>(fields).FirstOrDefault();
                        if (emailEntity != null)
                        {
                            tos.Add(new EmailAddress {
                                Name = emailEntity.FullName, Address = emailEntity.Email
                            });
                        }
                    }
                }
            }
            #endregion

            // Notice bhxh base joinday to 6 months.
            var bhxhs = dbContext.Employees.Find(m => m.Enable.Equals(true) && m.Leave.Equals(false)).ToEnumerable()
                        .Where(m => m.RemainingBhxh == 0).ToList();

            if (bhxhs.Count > 0)
            {
                foreach (var item in bhxhs)
                {
                    if (item != null)
                    {
                        var subject = "THÔNG BÁO ĐÓNG BHXH NHÂN VIÊN LÀM VIỆC 6 THÁNG !!!";
                        var title   = string.Empty;
                        if (!string.IsNullOrEmpty(item.Gender))
                        {
                            title = item.Gender == "Nam" ? "anh" : "chị";
                            if (item.AgeBirthday > 50)
                            {
                                title = item.Gender == "Nam" ? "ông" : "bà";
                            }
                        }
                        var fullName    = item.FullName;
                        var contractDay = string.Empty;
                        if (item.Contractday > Constants.MinDate)
                        {
                            contractDay = item.Contractday.ToString("dd/MM/yyyy");
                        }
                        var phone = string.Empty;
                        if (item.Mobiles != null && item.Mobiles.Count > 0)
                        {
                            foreach (var mobile in item.Mobiles)
                            {
                                if (!string.IsNullOrEmpty(mobile.Number))
                                {
                                    phone += "<a href='tel:" + mobile.Number + "'>" + mobile.Number + "</a>";
                                }
                            }
                        }

                        var email = string.IsNullOrEmpty(item.Email) ? string.Empty : item.Email;

                        var linkInformation = Constants.LinkHr.Main + "/" + Constants.LinkHr.Human + "/" + Constants.LinkHr.Information + "/" + item.Id;

                        //var ccs = new List<EmailAddress>();
                        //if (!string.IsNullOrEmpty(item.Email) && Utility.IsValidEmail(item.Email))
                        //{
                        //    ccs.Add(new EmailAddress { Name = item.FullName, Address = item.Email });
                        //}

                        var pathToFile  = @"C:\Projects\App.Schedule\Templates\AlertBhxh.html";
                        var bodyBuilder = new BodyBuilder();
                        using (StreamReader SourceReader = File.OpenText(pathToFile))
                        {
                            bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                        }
                        string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                           subject,
                                                           title + " " + fullName,
                                                           item.ChucVuName,
                                                           item.PhongBanName,
                                                           item.BoPhanName,
                                                           item.Joinday.ToString("dd/MM/yyyy"),
                                                           contractDay,
                                                           phone,
                                                           email,
                                                           url + "/" + linkInformation,
                                                           url);
                        var emailMessage = new EmailMessage()
                        {
                            FromAddresses = froms,
                            ToAddresses   = tos,
                            Subject       = subject,
                            BodyContent   = messageBody,
                            Type          = "alert-bhxh",
                            EmployeeId    = item.Id
                        };

                        var scheduleEmail = new ScheduleEmail
                        {
                            Status     = (int)EEmailStatus.Schedule,
                            To         = emailMessage.ToAddresses,
                            CC         = emailMessage.CCAddresses,
                            BCC        = emailMessage.BCCAddresses,
                            Type       = emailMessage.Type,
                            Title      = emailMessage.Subject,
                            Content    = emailMessage.BodyContent,
                            EmployeeId = emailMessage.EmployeeId
                        };
                        dbContext.ScheduleEmails.InsertOne(scheduleEmail);
                    }
                }
            }
        }
Esempio n. 14
0
        public void SendMailRegister(Employee entity)
        {
            var password    = Guid.NewGuid().ToString("N").Substring(0, 12);
            var sysPassword = Helper.HashedPassword(password);

            var filterUpdate = Builders <Employee> .Filter.Eq(m => m.Id, entity.Id);

            var update = Builders <Employee> .Update
                         .Set(m => m.Password, sysPassword);

            dbContext.Employees.UpdateOne(filterUpdate, update);

            var title = string.Empty;

            if (!string.IsNullOrEmpty(entity.Gender))
            {
                if (entity.AgeBirthday > 50)
                {
                    title = entity.Gender == "Nam" ? "anh" : "chị";
                }
            }
            var url     = Constants.System.domain;
            var subject = "Thông tin đăng nhập hệ thống.";
            var tos     = new List <EmailAddress>
            {
                new EmailAddress {
                    Name = entity.FullName, Address = entity.Email
                }
            };
            var pathToFile = _env.WebRootPath
                             + Path.DirectorySeparatorChar.ToString()
                             + "Templates"
                             + Path.DirectorySeparatorChar.ToString()
                             + "EmailTemplate"
                             + Path.DirectorySeparatorChar.ToString()
                             + "Confirm_Account_Registration.html";
            var builder = new BodyBuilder();

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                builder.HtmlBody = SourceReader.ReadToEnd();
            }
            string messageBody = string.Format(builder.HtmlBody,
                                               subject,
                                               title + " " + entity.FullName,
                                               url,
                                               entity.UserName,
                                               password,
                                               entity.Email);

            var emailMessage = new EmailMessage()
            {
                ToAddresses = tos,
                Subject     = subject,
                BodyContent = messageBody,
                Type        = "thong-tin-dang-nhap"
            };

            // For faster update.
            var scheduleEmail = new ScheduleEmail
            {
                Status  = (int)EEmailStatus.Schedule,
                To      = emailMessage.ToAddresses,
                CC      = emailMessage.CCAddresses,
                BCC     = emailMessage.BCCAddresses,
                Type    = emailMessage.Type,
                Title   = emailMessage.Subject,
                Content = emailMessage.BodyContent
            };

            dbContext.ScheduleEmails.InsertOne(scheduleEmail);
            //_emailSender.SendEmail(emailMessage);
        }
Esempio n. 15
0
        public IActionResult ApprovePost(string id, int approve, string secure)
        {
            var viewModel = new LeaveViewModel
            {
                Approve = approve
            };
            var leave = dbContext.Leaves.Find(m => m.Id.Equals(id)).FirstOrDefault();

            #region Extensions
            var builderTraining = Builders <Trainning> .Filter;
            var filterTraining  = builderTraining.Eq(m => m.Enable, true);
            filterTraining = filterTraining & builderTraining.Eq(m => m.Type, "anh-van");
            var listTraining = dbContext.Trainnings.Find(filterTraining).Limit(10).SortByDescending(m => m.CreatedOn).ToList();
            viewModel.ListTraining = listTraining;
            #endregion

            if (leave == null)
            {
                ViewData["Status"] = Constants.ErrorParameter;

                return(View(viewModel));
            }

            if (leave.SecureCode != secure && leave.Status != 0)
            {
                return(Json(new { result = true, message = Constants.ErrorParameter }));
            }

            viewModel.Leave = leave;

            #region Update status
            var filter = Builders <Leave> .Filter.Eq(m => m.Id, id);

            var update = Builders <Leave> .Update
                         .Set(m => m.SecureCode, Helper.HashedPassword(Guid.NewGuid().ToString("N").Substring(0, 12)))
                         .Set(m => m.Status, approve)
                         .Set(m => m.ApprovedBy, leave.ApproverId);

            dbContext.Leaves.UpdateOne(filter, update);
            #endregion

            #region update Leave Date if CANCEL
            if (approve == (int)StatusLeave.Cancel)
            {
                #region QUAN LY LOAI PHEP, BU, NGHI KO TINH LUONG,...
                var typeLeave = dbContext.LeaveTypes.Find(m => m.Id.Equals(leave.TypeId)).FirstOrDefault();
                // Nghi phep
                if (typeLeave.Alias == "phep-nam")
                {
                    var builderLeaveEmployee = Builders <LeaveEmployee> .Filter;
                    var filterLeaveEmployee  = builderLeaveEmployee.Eq(m => m.EmployeeId, leave.EmployeeId)
                                               & builderLeaveEmployee.Eq(x => x.LeaveTypeId, leave.TypeId);
                    var updateLeaveEmployee = Builders <LeaveEmployee> .Update.Inc(m => m.Number, leave.Number);

                    dbContext.LeaveEmployees.UpdateOne(filterLeaveEmployee, updateLeaveEmployee);
                }
                // Phep khac,...
                #endregion
            }
            #endregion

            var approvement = dbContext.Employees.Find(m => m.Id.Equals(leave.ApproverId)).FirstOrDefault();
            // Tự yêu cầu
            bool seftFlag   = leave.EmployeeId == leave.CreatedBy ? true : false;
            var  employee   = dbContext.Employees.Find(m => m.Id.Equals(leave.EmployeeId)).FirstOrDefault();
            var  userCreate = employee;
            if (!seftFlag)
            {
                userCreate = dbContext.Employees.Find(m => m.Id.Equals(leave.CreatedBy)).FirstOrDefault();
            }

            #region Send email to user leave
            var requester = employee.FullName;
            var tos       = new List <EmailAddress>();
            var ccs       = new List <EmailAddress>();
            tos.Add(new EmailAddress {
                Name = employee.FullName, Address = employee.Email
            });

            // Send mail to HR: if approve = 1;
            if (approve == 1)
            {
                var listHrRoles = dbContext.RoleUsers.Find(m => m.Role.Equals(Constants.Rights.NhanSu) && (m.Expired.Equals(null) || m.Expired > DateTime.Now)).ToList();
                if (listHrRoles != null && listHrRoles.Count > 0)
                {
                    foreach (var item in listHrRoles)
                    {
                        if (item.Action == 3)
                        {
                            var fields = Builders <Employee> .Projection.Include(p => p.Email).Include(p => p.FullName);

                            var emailEntity = dbContext.Employees.Find(m => m.Id.Equals(item.User) && m.Enable.Equals(true) && m.Leave.Equals(false)).Project <Employee>(fields).FirstOrDefault();
                            if (emailEntity != null)
                            {
                                tos.Add(new EmailAddress {
                                    Name = emailEntity.FullName, Address = emailEntity.Email
                                });
                            }
                        }
                    }
                }
                requester += " , HR";
            }

            // cc người tạo dùm
            if (!seftFlag)
            {
                ccs.Add(new EmailAddress {
                    Name = userCreate.FullName, Address = userCreate.Email
                });
            }

            // cc người duyệt
            ccs.Add(new EmailAddress {
                Name = approvement.FullName, Address = approvement.Email
            });

            var webRoot    = Environment.CurrentDirectory;
            var pathToFile = _env.WebRootPath
                             + Path.DirectorySeparatorChar.ToString()
                             + "Templates"
                             + Path.DirectorySeparatorChar.ToString()
                             + "EmailTemplate"
                             + Path.DirectorySeparatorChar.ToString()
                             + "LeaveApprove.html";

            #region parameters
            //{0} : Subject
            //{1} : Nguoi gui yeu cau  - Nguoi tao yeu cau (dùm)
            //{2} : Tình trạng (đồng ý/hủy)
            //{3} : Nguoi duyet
            //{4} : Email
            //{5} : Chức vụ
            //{6} : Date (từ, đến, số ngày)
            //{7} : Lý do
            //{8} : Loại phép
            //{9} : Số điện thoại liên hệ
            //{10}: Link chi tiết
            //{11}: Website
            #endregion
            var status      = approve == 1 ? "Đồng ý" : "Không đồng ý";
            var dateRequest = leave.From.ToString("dd/MM/yyyy HH:mm") + " - " + leave.To.ToString("dd/MM/yyyy HH:mm");

            var subject = "[Nghỉ phép] Kết quả duyệt: " + status + " - ngày " + dateRequest;

            var countLeaveDay = " (" + leave.Number + " ngày)";

            var linkDetail  = Constants.System.domain + "/" + Constants.LinkLeave.Main + "/" + Constants.LinkLeave.Index;
            var bodyBuilder = new BodyBuilder();
            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
            }
            string messageBody = string.Format(bodyBuilder.HtmlBody,
                                               subject,
                                               requester,
                                               status,
                                               approvement.FullName,
                                               approvement.Email,
                                               approvement.ChucVuName,
                                               dateRequest + countLeaveDay,
                                               leave.Reason,
                                               leave.TypeName,
                                               leave.Phone,
                                               linkDetail,
                                               Constants.System.domain
                                               );

            var emailMessage = new EmailMessage()
            {
                ToAddresses = tos,
                CCAddresses = ccs,
                Subject     = subject,
                BodyContent = messageBody,
                Type        = "leave-confirm",
                EmployeeId  = leave.EmployeeId
            };

            // For faster. Add to schedule.
            // Send later
            var scheduleEmail = new ScheduleEmail
            {
                Status     = (int)EEmailStatus.Schedule,
                To         = emailMessage.ToAddresses,
                CC         = emailMessage.CCAddresses,
                BCC        = emailMessage.BCCAddresses,
                Type       = emailMessage.Type,
                Title      = emailMessage.Subject,
                Content    = emailMessage.BodyContent,
                EmployeeId = emailMessage.EmployeeId
            };
            dbContext.ScheduleEmails.InsertOne(scheduleEmail);

            #endregion

            return(Json(new { result = true, message = "Cám ơn đã xác nhận, kết quả đang gửi cho người liên quan." }));
        }
Esempio n. 16
0
        public async Task <IActionResult> Create(LeaveViewModel viewModel)
        {
            #region Authorization
            LoginInit(string.Empty, (int)ERights.View);
            if (!(bool)ViewData[Constants.ActionViews.IsLogin])
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                return(RedirectToAction(Constants.ActionViews.Login, Constants.Controllers.Account));
            }
            var loginId = User.Identity.Name;
            var loginE  = dbContext.Employees.Find(m => m.Id.Equals(loginId)).FirstOrDefault();
            #endregion

            double phepcon = 0;
            var    entity  = viewModel.Leave;
            if (string.IsNullOrEmpty(entity.EmployeeId))
            {
                return(Json(new { result = false, message = "Lỗi: Vui lòng chọn nhân viên." }));
            }

            var isMe     = entity.EmployeeId == loginId ? true : false;
            var account  = isMe ? loginE : dbContext.Employees.Find(m => m.Id.Equals(entity.EmployeeId)).FirstOrDefault();
            var approveE = new Employee();
            if (isMe)
            {
                approveE = dbContext.Employees.Find(m => m.Id.Equals(entity.ApproverId)).FirstOrDefault();
                if (approveE == null)
                {
                    return(Json(new { result = false, message = "Lỗi: Vui lòng chọn người duyệt phép." }));
                }
                else
                {
                    entity.ApproverName = approveE.FullName + " - " + approveE.ChucVuName;
                }
            }

            #region Fill Data
            var workdayStartTime = TimeSpan.Parse(entity.WorkingScheduleTime.Split("-")[0]);
            var workdayEndTime   = TimeSpan.Parse(entity.WorkingScheduleTime.Split("-")[1]);
            entity.From   = entity.From.Date.Add(entity.Start);
            entity.To     = entity.To.Date.Add(entity.End);
            entity.Number = Utility.GetBussinessDaysBetweenTwoDates(entity.From, entity.To, workdayStartTime, workdayEndTime);

            #region QUAN LY LOAI PHEP, BU, NGHI KO TINH LUONG,...
            var typeLeave = dbContext.LeaveTypes.Find(m => m.Id.Equals(entity.TypeId)).FirstOrDefault();
            if (typeLeave.SalaryPay == true)
            {
                double leaveDayAvailable = 0;
                // Get phép năm, bù còn
                var leaveEmployeePhep = dbContext.LeaveEmployees.Find(m => m.EmployeeId.Equals(entity.EmployeeId) && m.LeaveTypeId.Equals(entity.TypeId)).FirstOrDefault();
                if (leaveEmployeePhep != null)
                {
                    leaveDayAvailable = leaveEmployeePhep.Number;
                }
                // Nghỉ hưởng lương dc phép tạo (thai sản, cưới, sự kiện,...)
                if (typeLeave.Alias != "nghi-huong-luong")
                {
                    if (leaveDayAvailable < entity.Number)
                    {
                        return(Json(new { result = false, message = typeLeave.Name + " không đủ ngày." }));
                    }
                }
            }
            #endregion

            #region Tạo trùng ngày
            var builderExist = Builders <Leave> .Filter;
            var filterExist  = builderExist.Eq(m => m.Enable, true);
            filterExist &= builderExist.Eq(m => m.EmployeeId, entity.EmployeeId);
            filterExist &= builderExist.Gte(m => m.From, entity.From);
            filterExist &= builderExist.Lte(m => m.To, entity.To);

            var exists = await dbContext.Leaves.Find(filterExist).ToListAsync();

            if (exists != null && exists.Count > 0)
            {
                return(Json(new { result = false, message = "Ngày yêu cầu đã được duyệt. Xem danh sách nghỉ bên dưới. Vui lòng yêu cầu ngày khác." }));
            }
            #endregion

            entity.SecureCode         = Helper.HashedPassword(Guid.NewGuid().ToString("N").Substring(0, 12));
            entity.EmployeeName       = account.FullName;
            entity.EmployeeDepartment = account.PhongBanName;
            entity.EmployeePart       = account.BoPhanName;
            entity.EmployeeTitle      = account.ChucVuName;
            entity.Status             = (int)StatusLeave.New;
            entity.CreatedBy          = loginE.Id;
            entity.UpdatedBy          = loginE.Id;
            if (!isMe)
            {
                entity.Status       = (int)StatusLeave.Accept;
                entity.ApproverId   = loginE.Id;
                entity.ApproverName = loginE.FullName + " - " + loginE.ChucVuName;
                entity.ApprovedBy   = loginE.Id;
            }
            #endregion

            dbContext.Leaves.InsertOne(entity);

            #region CAP NHAT PHEP, BU, NGHI KO TINH LUONG,...
            if (typeLeave.SalaryPay == true)
            {
                #region update Leave Date
                // phep nam, bu
                // Nghỉ hưởng lương dc phép tạo (thai sản, cưới, sự kiện,...)
                if (typeLeave.Alias != "nghi-huong-luong")
                {
                    var builderLeaveEmployee = Builders <LeaveEmployee> .Filter;
                    var filterLeaveEmployee  = builderLeaveEmployee.Eq(m => m.EmployeeId, entity.EmployeeId)
                                               & builderLeaveEmployee.Eq(x => x.LeaveTypeId, entity.TypeId);
                    var updateLeaveEmployee = Builders <LeaveEmployee> .Update.Inc(m => m.Number, -entity.Number)
                                              .Inc(m => m.NumberUsed, entity.Number);

                    dbContext.LeaveEmployees.UpdateOne(filterLeaveEmployee, updateLeaveEmployee);
                }
                #endregion

                phepcon = dbContext.LeaveEmployees.AsQueryable().Where(x => x.EmployeeId.Equals(entity.EmployeeId)).Sum(x => x.Number);
            }
            #endregion

            #region Send Mail
            if (isMe)
            {
                var tos = new List <EmailAddress>();
                if (!string.IsNullOrEmpty(entity.ApproverId))
                {
                    tos.Add(new EmailAddress {
                        Name = approveE.FullName, Address = approveE.Email
                    });
                }
                var webRoot    = Environment.CurrentDirectory;
                var pathToFile = _env.WebRootPath
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "Templates"
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "EmailTemplate"
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "LeaveRequest.html";

                var subject     = "Xác nhận nghỉ phép.";
                var requester   = account.FullName;
                var var3        = account.FullName;
                var dateRequest = entity.From.ToString("dd/MM/yyyy HH:mm") + " - " + entity.To.ToString("dd/MM/yyyy HH:mm") + " (" + entity.Number + " ngày)";
                // Api update, generate code.
                var linkapprove = Constants.System.domain + "/xacnhan/phep";
                var linkAccept  = linkapprove + "?id=" + entity.Id + "&approve=1&secure=" + entity.SecureCode;
                var linkCancel  = linkapprove + "?id=" + entity.Id + "&approve=2&secure=" + entity.SecureCode;
                var linkDetail  = Constants.System.domain;
                var bodyBuilder = new BodyBuilder();
                using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                {
                    bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                }
                string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                   subject,
                                                   approveE.FullName,
                                                   requester,
                                                   var3,
                                                   approveE.Email,
                                                   account.ChucVuName,
                                                   dateRequest,
                                                   entity.Reason,
                                                   entity.TypeName,
                                                   entity.Phone,
                                                   linkAccept,
                                                   linkCancel,
                                                   linkDetail,
                                                   Constants.System.domain
                                                   );

                var emailMessage = new EmailMessage()
                {
                    ToAddresses = tos,
                    Subject     = subject,
                    BodyContent = messageBody,
                    Type        = "yeu-cau-nghi-phep",
                    EmployeeId  = account.Id
                };
                var scheduleEmail = new ScheduleEmail
                {
                    Status     = (int)EEmailStatus.Schedule,
                    To         = emailMessage.ToAddresses,
                    CC         = emailMessage.CCAddresses,
                    BCC        = emailMessage.BCCAddresses,
                    Type       = emailMessage.Type,
                    Title      = emailMessage.Subject,
                    Content    = emailMessage.BodyContent,
                    EmployeeId = emailMessage.EmployeeId
                };
                dbContext.ScheduleEmails.InsertOne(scheduleEmail);
            }
            else
            {
                // KO CÓ EMAIL,...
                // [To] nếu có email, người tạo
                var tos = new List <EmailAddress>();
                if (!string.IsNullOrEmpty(account.Email))
                {
                    tos.Add(new EmailAddress {
                        Name = account.FullName, Address = account.Email
                    });
                }

                tos.Add(new EmailAddress {
                    Name = loginE.FullName, Address = loginE.Email
                });

                var ccs = new List <EmailAddress>();
                var hrs = Utility.EmailGet(Constants.Rights.NhanSu, (int)ERights.Edit);
                if (hrs != null && hrs.Count > 0)
                {
                    foreach (var item in hrs)
                    {
                        if (tos.Count(m => m.Address.Equals(item.Address)) == 0)
                        {
                            ccs.Add(item);
                        }
                    }
                }

                var webRoot    = Environment.CurrentDirectory;
                var pathToFile = _env.WebRootPath
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "Templates"
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "EmailTemplate"
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "LeaveHelp.html";

                var subject     = "Thông tin nghỉ phép.";
                var dateRequest = entity.From.ToString("dd/MM/yyyy HH:mm") + " - " + entity.To.ToString("dd/MM/yyyy HH:mm") + " (" + entity.Number + " ngày)";
                // Api update, generate code.
                var linkDetail  = Constants.System.domain;
                var bodyBuilder = new BodyBuilder();
                using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                {
                    bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                }
                string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                   subject,
                                                   account.FullName,
                                                   loginE.FullName,
                                                   dateRequest,
                                                   entity.Reason,
                                                   entity.TypeName,
                                                   entity.Phone,
                                                   linkDetail,
                                                   Constants.System.domain
                                                   );

                var emailMessage = new EmailMessage()
                {
                    ToAddresses = tos,
                    CCAddresses = ccs,
                    Subject     = subject,
                    BodyContent = messageBody,
                    Type        = "nghi-phep-thong-tin",
                    EmployeeId  = account.Id
                };
                var scheduleEmail = new ScheduleEmail
                {
                    Status     = (int)EEmailStatus.Schedule,
                    To         = emailMessage.ToAddresses,
                    CC         = emailMessage.CCAddresses,
                    BCC        = emailMessage.BCCAddresses,
                    Type       = emailMessage.Type,
                    Title      = emailMessage.Subject,
                    Content    = emailMessage.BodyContent,
                    EmployeeId = emailMessage.EmployeeId
                };
                dbContext.ScheduleEmails.InsertOne(scheduleEmail);
            }
            #endregion

            return(Json(new { result = true, message = "Thông tin sẽ được gửi các bộ phận liên quan, thời gian tùy theo qui định của công ty và các yếu tố khách quan." }));
        }