You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

433 lines
17 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
  1. using Microsoft.AspNet.Identity;
  2. using Microsoft.AspNet.Identity.EntityFramework;
  3. using Microsoft.Owin.Security;
  4. using Sevomin.Models;
  5. using Sevomin.Models.Enums;
  6. using Sevomin.Models.Helpers;
  7. using Sevomin.Models.Repositories;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.ServiceModel.Syndication;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using System.Web;
  15. using System.Web.Mvc;
  16. using System.Xml;
  17. namespace Sevomin.WebFrontend.Controllers
  18. {
  19. public class JobController : AuthorizedController
  20. {
  21. IAdRepository _adRepository;
  22. IJobRepository _jobRepository;
  23. private HttpContextBase _httpContext;
  24. public JobController()
  25. : this(AdRepository.Current, JobRepository.Current,
  26. new SevominUserManager(new UserStore<User>(SevominDbContext.Current)), null)
  27. {
  28. }
  29. protected override void Initialize(System.Web.Routing.RequestContext requestContext)
  30. {
  31. base.Initialize(requestContext);
  32. _httpContext = requestContext.HttpContext;
  33. }
  34. public JobController(IAdRepository adRepository, IJobRepository jobRepository, SevominUserManager userManager, HttpContextBase httpContext) : base(userManager)
  35. {
  36. _adRepository = adRepository;
  37. _jobRepository = jobRepository;
  38. _httpContext = httpContext;
  39. }
  40. private async Task<Job> GetEmptyJob()
  41. {
  42. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  43. if (u == null)
  44. throw new InvalidOperationException("شما خیلی هنرمندی! به ما هم بگو چجوری!");
  45. Avalin avalin = u as Avalin;
  46. if (avalin == null)
  47. throw new InvalidOperationException("جای شما که اینجا نیست!");
  48. Job job = _jobRepository.GetEmptyJobFor(avalin);
  49. return job;
  50. }
  51. [Authorize(Roles = "Avalin")]
  52. public async Task<ActionResult> NewJob()
  53. {
  54. Avalin u = await UserManager.FindByNameAsync(User.Identity.Name) as Avalin;
  55. Job job = await GetEmptyJob();
  56. JobViewModel jvm = new JobViewModel(job);
  57. if (u == null)
  58. throw new InvalidOperationException();
  59. if (!u.EmailConfirmed)
  60. {
  61. ViewBag.Result = new PostResultViewModel(false, "ایمیل شما در سایت تایید نشده است. لطفا پس از تایید ایمیل برای تعریف این فرصت شغلی اقدام نمایید.");
  62. return View(jvm);
  63. }
  64. return View(jvm);
  65. }
  66. [Authorize(Roles = "Avalin")]
  67. [HttpPost]
  68. public async Task<ActionResult> NewJob(string JalaliExpireDate, string ContactPersonName,
  69. string ContactPersonPhone, string ContactPersonEMail, bool IsFullTime,
  70. bool ShowCompanyName, string Description, bool ShowCompanyLogo, ResumeTypes ResumeType, FormCollection form)
  71. {
  72. Avalin u = await UserManager.FindByNameAsync(User.Identity.Name) as Avalin;
  73. Job job = await GetEmptyJob();
  74. if (u == null)
  75. throw new InvalidOperationException();
  76. if (!u.EmailConfirmed)
  77. {
  78. ViewBag.Result = new PostResultViewModel(false, "ایمیل شما در سایت تایید نشده است. لطفا پس از تایید ایمیل برای تعریف این فرصت شغلی اقدام نمایید.");
  79. return View(new JobViewModel(job));
  80. }
  81. try
  82. {
  83. UpdateFields(JalaliExpireDate, ContactPersonName, ContactPersonPhone,
  84. ContactPersonEMail, IsFullTime, ShowCompanyName,
  85. Description, ShowCompanyLogo, ResumeType, form, job);
  86. JobRepository.Current.Save();
  87. try
  88. {
  89. foreach (var dovomin in UserRepository.Current.ListAll().Where(user => user is Dovomin && user.EmailConfirmed))
  90. {
  91. SevominEmailer emailer = new SevominEmailer {EmailType = EmailType.NewJob};
  92. emailer.Parameters.Add("display-name", dovomin.DisplayName);
  93. emailer.Parameters.Add("job-description", job.Description);
  94. emailer.Parameters.Add("job-link", job.Id.ToString());
  95. await emailer.SendAsync(dovomin.Email, true, ((Dovomin)dovomin).OptOutEmail);
  96. }
  97. }
  98. catch (Exception e)
  99. {
  100. var elmah = new Elmah.Error(e);
  101. Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(elmah);
  102. }
  103. ViewBag.Result = new PostResultViewModel(true, "آگهی شما با موفقیت منتشر شد.");
  104. return RedirectToAction("SingleJob", new { jobId = job.Id });
  105. }
  106. catch (Exception)
  107. {
  108. ViewBag.Result = new PostResultViewModel(true, "در انتشار آگهی خطایی پیش آمده.");
  109. return View(new JobViewModel(job));
  110. }
  111. }
  112. private async Task<Job> FetchJob(long id)
  113. {
  114. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  115. if (u == null)
  116. throw new InvalidOperationException("شما خیلی هنرمندی! به ما هم بگو چجوری!");
  117. Avalin avalin = (Avalin)u;
  118. Job job = _jobRepository.Find(id);
  119. if (job == null || job.AvalinId != avalin.Id)
  120. throw new InvalidOperationException("شماره آگهی استخدام مورد نظر معتبر نیست");
  121. return job;
  122. }
  123. [Authorize(Roles= "Avalin")]
  124. public async Task<ActionResult> Edit(long id)
  125. {
  126. Job job = await FetchJob(id);
  127. if (job.AvalinId != (await UserManager.FindByNameAsync(User.Identity.Name)).Id)
  128. return HttpNotFound();
  129. JobViewModel jvm = new JobViewModel(job);
  130. return View(jvm);
  131. }
  132. [HttpPost]
  133. public async Task<ActionResult> Edit(long id, string JalaliExpireDate, string ContactPersonName,
  134. string ContactPersonPhone, string ContactPersonEMail, bool IsFullTime,
  135. bool ShowCompanyName, string Description, bool ShowCompanyLogo, ResumeTypes ResumeType, FormCollection form)
  136. {
  137. Job job = await FetchJob(id);
  138. if (job.AvalinId != (await UserManager.FindByNameAsync(User.Identity.Name)).Id)
  139. return HttpNotFound();
  140. try
  141. {
  142. UpdateFields(JalaliExpireDate, ContactPersonName, ContactPersonPhone,
  143. ContactPersonEMail, IsFullTime, ShowCompanyName,
  144. Description, ShowCompanyLogo, ResumeType, form, job);
  145. JobRepository.Current.Save();
  146. ViewBag.Result = new PostResultViewModel(true, "آگهی شما با موفقیت به روز رسانی شد.");
  147. return View(new JobViewModel(job));
  148. }
  149. catch (Exception)
  150. {
  151. ViewBag.Result = new PostResultViewModel(false, "در به روز رسانی آگهی خطایی پیش آمد.");
  152. return View(new JobViewModel(job));
  153. }
  154. }
  155. [AllowAnonymous]
  156. public ActionResult RecentJobs()
  157. {
  158. ViewBag.Ads = _adRepository.GetAds();
  159. return View(_jobRepository.ListAll()
  160. .Where(d => d.ExpireDate >= DateTime.UtcNow)
  161. .OrderByDescending(d => d.CreateDate).ThenByDescending(d => d.ExpireDate)
  162. .ToList()
  163. .Select(j => new JobMiniViewModel(j)).ToList());
  164. }
  165. [AllowAnonymous]
  166. public PartialViewResult LatestJobList(int count)
  167. {
  168. ViewBag.Ads = _adRepository.GetAds();
  169. return PartialView("JobList", _jobRepository.ListAll()
  170. .Where(d => d.ExpireDate >= DateTime.UtcNow)
  171. .OrderByDescending(d => d.CreateDate)
  172. .Take(count)
  173. .ToList()
  174. .Select(j => new JobMiniViewModel(j)).ToList());
  175. }
  176. [AllowAnonymous]
  177. public async Task<ActionResult> SingleJob(long jobId)
  178. {
  179. Job job = _jobRepository.Find(jobId);
  180. if (job == null)
  181. return HttpNotFound();
  182. JobViewModel viewModel = new JobViewModel(job);
  183. JobMiniViewModel jvm = new JobMiniViewModel(job, 3);
  184. ViewBag.ShortJobDescription = jvm.JobSummary;
  185. if (Request.IsAuthenticated && User.IsInRole("Dovomin"))
  186. {
  187. Dovomin user = await UserManager.FindByNameAsync(User.Identity.Name) as Dovomin;
  188. DovominJobViewModel djvm = new DovominJobViewModel(new DovominJob(user, job));
  189. ViewBag.MinimumRequirement = djvm.MinimumRequirement;
  190. ViewBag.Affinity = djvm.Affinity.ToString();
  191. }
  192. return View(viewModel);
  193. }
  194. [Authorize(Roles = "Dovomin")]
  195. public async Task<ActionResult> Apply(long jobId)
  196. {
  197. Dovomin user = (await UserManager.FindByNameAsync(User.Identity.Name)) as Dovomin;
  198. Job job = _jobRepository.Find(jobId);
  199. if (user == null || job == null)
  200. return HttpNotFound();
  201. bool alreadyApplied = job.Applications.Any(a => a.DovominId == user.Id);
  202. DovominJob dj = alreadyApplied ? job.Applications.First(a => a.DovominId == user.Id) : new DovominJob(user, job);
  203. dj.CalculateAffinity();
  204. PrepareJobApplication(user, job, alreadyApplied);
  205. return View(new DovominJobViewModel(dj));
  206. }
  207. [Authorize(Roles = "Dovomin")]
  208. [HttpPost]
  209. [ValidateAntiForgeryToken]
  210. public async Task<ActionResult> Apply(long jobId, string CoverLetter)
  211. {
  212. Dovomin user = (await UserManager.FindByNameAsync(User.Identity.Name)) as Dovomin;
  213. Job job = _jobRepository.Find(jobId);
  214. if (user == null || job == null)
  215. return HttpNotFound();
  216. bool alreadyApplied = job.Applications.Any(a => a.DovominId == user.Id);
  217. PrepareJobApplication(user, job, alreadyApplied);
  218. DovominJob dj = alreadyApplied ? job.Applications.First(a => a.DovominId == user.Id) : new DovominJob(user, job);
  219. dj.CalculateAffinity();
  220. if (alreadyApplied)
  221. {
  222. ViewBag.Result = new PostResultViewModel(false, "اعلام آمادگی شما برای این فرصت شغلی قبلا ثبت شده است.");
  223. return View(new DovominJobViewModel(dj));
  224. }
  225. else if (!user.EmailConfirmed)
  226. {
  227. ViewBag.Result = new PostResultViewModel(false, "ایمیل شما در سایت تایید نشده است. لطفا پس از تایید ایمیل خود، مجددا برای این فرصت شغلی اعلام آمادگی نمایید.");
  228. return View(new DovominJobViewModel(dj));
  229. }
  230. dj = _jobRepository.Apply(user, job, CoverLetter);
  231. /* Send instant email to Avalin */
  232. try
  233. {
  234. SevominEmailer emailer = new SevominEmailer();
  235. emailer.EmailType = EmailType.NewApplication;
  236. emailer.Parameters.Add("avalin-name", job.Avalin.DisplayName);
  237. emailer.Parameters.Add("avalin-contact", string.IsNullOrWhiteSpace(dj.Job.ContactPersonName) ? "" : dj.Job.ContactPersonName);
  238. emailer.Parameters.Add("dovomin-name", dj.Dovomin.DisplayName);
  239. await emailer.SendAsync(job.Avalin.Email, true, false);
  240. if (!string.IsNullOrWhiteSpace(dj.Job.ContactPersonEMail))
  241. {
  242. await emailer.SendAsync(dj.Job.ContactPersonEMail, true, false);
  243. }
  244. }
  245. catch (Exception e)
  246. {
  247. var elmah = new Elmah.Error(e);
  248. Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(elmah);
  249. }
  250. /* End send instant email to avalin */
  251. ViewBag.Result = new PostResultViewModel(true, "اعلام آمادگی شما برای این فرصت شغلی ثبت شد.");
  252. return View(new DovominJobViewModel(dj));
  253. }
  254. public ActionResult MyJobs(int? count)
  255. {
  256. User user = UserManager.FindByName(User.Identity.Name);
  257. List<JobMiniViewModel> retList = new List<JobMiniViewModel>();
  258. if (user is Avalin)
  259. retList = _jobRepository.ListAll()
  260. .Where(j => j.AvalinId == user.Id)
  261. .OrderByDescending(j => j.CreateDate)
  262. .ToList()
  263. .Select(j => new JobMiniViewModel(j))
  264. .ToList();
  265. else
  266. retList = _jobRepository.ListAll()
  267. .Where(j => j.Applications.Any(a => a.DovominId == user.Id))
  268. .OrderByDescending(j => j.CreateDate)
  269. .ToList()
  270. .Select(j => new JobMiniViewModel(j))
  271. .ToList();
  272. return PartialView("JobList", retList);
  273. }
  274. [Authorize(Roles = "Avalin")]
  275. public ActionResult JobRequests()
  276. {
  277. Avalin user = UserManager.FindByName(User.Identity.Name) as Avalin;
  278. if (user == null)
  279. return HttpNotFound();
  280. var applications = SevominDbContext.Current.DovominJobs
  281. .Where(a => a.Job.AvalinId == user.Id)
  282. .OrderByDescending(a => a.ApplyDate)
  283. .ToList()
  284. .Select(a => new JobApplicationViewModel(a));
  285. return PartialView(applications);
  286. }
  287. [AllowAnonymous]
  288. public ActionResult RecentJobsJavascript(int? count)
  289. {
  290. var jobs = _jobRepository.ListAll()
  291. .Where(d => d.ExpireDate >= DateTime.UtcNow)
  292. .OrderByDescending(d => d.CreateDate)
  293. .ToList()
  294. .Select(j => new JobMiniExternalViewModel(j)).ToList();
  295. if (count.HasValue)
  296. jobs = jobs.Take(count.Value).ToList();
  297. string json = Newtonsoft.Json.JsonConvert.SerializeObject(jobs);
  298. string js = System.IO.File.ReadAllText(System.IO.Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), @"export-assets\export.js")).Replace("$$jobs", json);
  299. return Content(js, "application/javascript");
  300. }
  301. [AllowAnonymous]
  302. public ActionResult RecentJobsRss()
  303. {
  304. SyndicationFeed feed = new SyndicationFeed("فرصت های شغلی جدید در سومین", "در این فید، فرصت های شغلی جدید سومین را دنبال کنید", new Uri("http://www.sevom.in/jobs"));
  305. feed.Authors.Add(new SyndicationPerson("[email protected]"));
  306. var jobs = _jobRepository.ListAll()
  307. .Where(d => d.ExpireDate >= DateTime.UtcNow)
  308. .OrderByDescending(d => d.CreateDate)
  309. .ToList()
  310. .Select(j => new JobMiniViewModel(j)).ToList();
  311. List<SyndicationItem> items = new List<SyndicationItem>();
  312. foreach (var job in jobs)
  313. {
  314. SyndicationItem jobRss = new SyndicationItem(job.JobSummary, "",
  315. new Uri(string.Format("http://www.sevom.in{0}", Url.Action("SingleJob", new { jobId = job.Id }))));
  316. items.Add(jobRss);
  317. }
  318. feed.Items = items;
  319. var rss2 = new Rss20FeedFormatter(feed);
  320. var outputXml = new StringBuilder();
  321. using (var writer = XmlWriter.Create(outputXml, new XmlWriterSettings { Indent = true }))
  322. {
  323. rss2.WriteTo(writer);
  324. writer.Flush();
  325. }
  326. return Content(outputXml.ToString(), "application/rss+xml");
  327. }
  328. private void PrepareJobApplication(Dovomin user, Job job, bool alreadyApplied = true)
  329. {
  330. JobMiniViewModel jvm = new JobMiniViewModel(job, 3);
  331. ViewBag.ShortJobDescription = jvm.JobSummary;
  332. ViewBag.Job = new JobViewModel(job);
  333. ViewBag.AlreadyApplied = alreadyApplied;
  334. }
  335. private static void UpdateFields(string JalaliExpireDate, string ContactPersonName, string ContactPersonPhone, string ContactPersonEMail, bool IsFullTime, bool ShowCompanyName, string Description, bool ShowCompanyLogo, ResumeTypes ResumeType, FormCollection form, Job job)
  336. {
  337. job.ExpireDate = DateAssist.ToMiladi(JalaliExpireDate);
  338. job.ContactPersonEMail = ContactPersonEMail;
  339. job.ContactPersonName = ContactPersonName;
  340. job.ContactPersonPhone = ContactPersonPhone;
  341. job.Description = Description;
  342. job.IsFullTime = IsFullTime;
  343. job.ShowCompanyLogo = ShowCompanyLogo;
  344. job.ShowCompanyName = ShowCompanyName;
  345. job.ResumeType = (byte)ResumeType;
  346. foreach (var jp in job.JobParameters)
  347. {
  348. string value = form[string.Format("value-{0}", jp.Parameter.Id)];
  349. byte moscow = 0;
  350. byte.TryParse(form[string.Format("moscow-{0}", jp.Parameter.Id)], out moscow);
  351. jp.SetValue(value);
  352. if (jp.Parameter.Moscow)
  353. {
  354. if (string.IsNullOrWhiteSpace(jp.StringValue))
  355. jp.Moscow = 0;
  356. else
  357. jp.Moscow = moscow;
  358. }
  359. else
  360. {
  361. jp.Moscow = 4;
  362. }
  363. }
  364. }
  365. }
  366. }