public void UpdateWebsite(string regionId, String regionWebsite) { KawalDesaController.CheckRegionAllowed(dbContext, regionId); Update(regionId) .Set(e => e.Website, regionWebsite) .Save(); }
public void SetAnonymous(bool isAnonymous) { var user = KawalDesaController.GetCurrentUser(); ModelController <User, string> .Update(dbContext, user.Id) .Set(e => e.IsAnonymous, isAnonymous) .Save(); }
public void Complete(long apbdesId) { var apbdes = dbSet.Find(apbdesId); //if (apbdes.IsCompleted) //throw new ApplicationException("apbdes is completed"); KawalDesaController.CheckRegionAllowed(dbContext, apbdes.fkRegionId); //apbdes.IsCompleted = true; dbContext.Entry(apbdes).State = EntityState.Modified; dbContext.SaveChanges(); }
public void Upload(Multipart <Spreadsheet> multipart, AdapterContext context) { try { List <Region> regions = null; if (context.Region.Type == RegionType.NASIONAL) { regions = DbContext.Set <Region>().Where(r => r.Type == RegionType.KABUPATEN).ToList(); } else { regions = DbContext.Set <Region>().Where(r => r.Type == RegionType.DESA && r.Parent.fkParentId == context.Region.Id).ToList(); } var allocations = new AllocationSpreadsheetReader <TAllocation>().Read(regions, new FileInfo(multipart.Files[0].FilePath)); var spreadsheet = multipart.Entity; var user = KawalDesaController.GetCurrentUser(); var fileResult = multipart.Files[0]; var blob = new Blob(fileResult); DbContext.Set <Blob>().Add(blob); DbContext.SaveChanges(); fileResult.Move(blob.FilePath); spreadsheet.FileName = blob.RelativeFileName; spreadsheet.fkCreatedById = user.Id; spreadsheet.fkOrganizationId = user.fkOrganizationId.Value; spreadsheet.DateCreated = DateTime.Now; spreadsheet.DateActivated = DateTime.Now; spreadsheet.Type = context.Type; spreadsheet.ApbnKey = context.Apbn.Key; spreadsheet.fkRegionId = context.Region.Id; spreadsheet.fkFileId = blob.Id; DbContext.Set <Spreadsheet>().Add(spreadsheet); DbContext.SaveChanges(); foreach (var allocation in allocations) { allocation.fkSpreadsheetId = spreadsheet.Id; Init(context, allocation); DbContext.Set <TAllocation>().Add(allocation); } DbContext.SaveChanges(); new SpreadsheetActivator <TAllocation>().Activate(DbContext, spreadsheet); } finally { multipart.DeleteUnmoved(); } }
public UserViewModel AddOrgVolunteer(long id, String email) { using (var tx = dbContext.Database.BeginTransaction()) { var org = dbSet.Find(id); var roles = new List <string> { Role.VOLUNTEER }; User inviter = dbContext.Set <User>().Find(KawalDesaController.GetCurrentUser().Id); var token = InvitationToken.Create(dbContext, email, inviter, org, roles, new List <Region>()); new UserMailer().Invitation(token).Deliver(); tx.Commit(); return(userController.Convert(token.User)); } }
public void Upload(Multipart <Spreadsheet> multipart, int type, string regionId, string apbnKey) { KawalDesaController.CheckRegionAllowed(dbContext, regionId); DocumentUploadType t = (DocumentUploadType)type; var context = new AdapterContext(dbContext, t, regionId, apbnKey); if (context.Region.Type != RegionType.NASIONAL && context.Region.Type != RegionType.KABUPATEN) { throw new ApplicationException("only allowed to upload on nasional or kabupaten"); } using (var tx = dbContext.Database.BeginTransaction()) { adapters[t].Upload(multipart, context); tx.Commit(); } }
public UserViewModel AddOrgAdmin(long id, String email) { using (var tx = dbContext.Database.BeginTransaction()) { var org = dbSet.Find(id); var roles = new List <string> { Role.VOLUNTEER_ALLOCATION, Role.VOLUNTEER_TRANSFER, Role.VOLUNTEER_DESA, Role.VOLUNTEER_ACCOUNT, Role.VOLUNTEER_REALIZATION, Role.ORGANIZATION_ADMIN, Role.VOLUNTEER }; var national = dbContext.Set <Region>().Find("0"); User inviter = dbContext.Set <User>().Find(KawalDesaController.GetCurrentUser().Id); var token = InvitationToken.Create(dbContext, email, inviter, org, roles, new List <Region> { national }); new UserMailer().Invitation(token).Deliver(); tx.Commit(); return(userController.Convert(token.User)); } }
public void AddAccounts(long apbdesId, long rootAccountId, [FromBody] List <Account> accounts) { /* Fetches */ var apbdes = Get(apbdesId); //if (apbdes.IsCompleted) //throw new ApplicationException("apbdes is completed"); KawalDesaController.CheckRegionAllowed(dbContext, apbdes.fkRegionId); var rootAccount = dbContext.Set <Account>().Find(rootAccountId); var existingAccounts = apbdes.Accounts .Where(a => a.Type == rootAccount.Type) .ToList(); var allAccounts = existingAccounts .Union(accounts) .ToList(); /* Cleanups */ foreach (var account in accounts) { if (!string.IsNullOrEmpty(account.Code)) { account.Code = Regex.Replace(account.Code, @"\s+", ""); account.Type = rootAccount.Type; account.fkApbdesId = apbdes.Id; } } /* Validate */ this.ModelState.Clear(); this.Validate(accounts); if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } var invalids = new List <Invalid>(); var accountCodesSet = new HashSet <String>(existingAccounts.Select(e => e.Code)); for (var i = 0; i < accounts.Count; i++) { var field = String.Format("[{0}].{1}", i, "Code"); var account = accounts[i]; if (!Regex.IsMatch(account.Code, @"[\d\.]+")) { invalids.Add(new Invalid(field, "Kode tidak valid")); } if (accountCodesSet.Contains(account.Code)) { invalids.Add(new Invalid(field, "Kode sudah terdaftar")); } accountCodesSet.Add(account.Code); var parentCode = account.ParentCode; if (!allAccounts.Any(a => a.Code == parentCode)) { invalids.Add(new Invalid(field, "Anggaran tidak mempunyai induk anggaran")); } } this.ValidateWith(invalids); /* Persist */ foreach (var account in accounts.OrderBy(a => a.Code)) { var parentAccount = allAccounts.First(a => a.Code == account.ParentCode); account.fkParentAccountId = parentAccount.Id; dbContext.Set <Account>().Add(account); dbContext.SaveChanges(); } foreach (var account in accounts.OrderByDescending(a => a.Code)) { var childAccounts = allAccounts.Where(a => a.ParentCode == account.Code).ToList(); if (childAccounts.Count > 0) { account.Amount = null; dbContext.Entry(account).State = EntityState.Modified; dbContext.SaveChanges(); } } }
public UserViewModel GetCurrentUser() { var user = KawalDesaController.GetCurrentUser(); return(Convert(user)); }
public void Publish(Stream fileStream, AdapterContext context, string notes) { try { List <Region> regions = null; if (context.Region.Type == RegionType.NASIONAL) { regions = DbContext.Set <Region>().Where(r => r.Type == RegionType.KABUPATEN).ToList(); } else { regions = DbContext.Set <Region>().Where(r => r.Type == RegionType.DESA && r.Parent.fkParentId == context.Region.Id).ToList(); } Blob blob = new Blob(); blob.Name = "Alocation_xxx.xlsx"; DbContext.Set <Blob>().Add(blob); DbContext.SaveChanges(); byte[] fileBytes = null; using (MemoryStream ms = new MemoryStream()) { fileStream.CopyTo(ms); fileBytes = ms.ToArray(); } string fileName = blob.Id + ".xlsx"; string root = HttpContext.Current.Server.MapPath("~/Content/Files"); var user = KawalDesaController.GetCurrentUser(); Directory.CreateDirectory(root); String filePath = Path.Combine(root, fileName); File.WriteAllBytes(filePath, fileBytes); Spreadsheet spreadsheet = new Spreadsheet(); spreadsheet.File = blob; spreadsheet.Notes = notes; spreadsheet.fkCreatedById = user.Id; spreadsheet.fkOrganizationId = user.fkOrganizationId.Value; spreadsheet.DateCreated = DateTime.Now; spreadsheet.DateActivated = DateTime.Now; spreadsheet.Type = context.Type; spreadsheet.ApbnKey = context.Apbn.Key; spreadsheet.fkRegionId = context.Region.Id; spreadsheet.fkFileId = blob.Id; DbContext.Set <Spreadsheet>().Add(spreadsheet); DbContext.SaveChanges(); var allocations = new AllocationSpreadsheetReader <TAllocation>().Read(regions, fileBytes); foreach (var allocation in allocations) { allocation.fkSpreadsheetId = spreadsheet.Id; Init(context, allocation); DbContext.Set <TAllocation>().Add(allocation); } DbContext.SaveChanges(); new SpreadsheetActivator <TAllocation>().Activate(DbContext, spreadsheet); } catch (Exception ex) { throw ex; } }
public String GetCurrentSheetUrl(DocumentUploadType type, string regionId, string apbnKey) { User user = KawalDesaController.GetCurrentUser(); var context = new AdapterContext(dbContext, type, regionId, apbnKey); var region = dbContext.Set <Region>().Find(regionId); String userId = user != null ? user.Id : null; String userEmail = user != null ? user.Email : null; String userName = user != null ? user.Name : "Anonymous"; var workItem = dbContext.Set <SpreadsheetWorkItem>() .FirstOrDefault(w => w.fkUserId == userId && w.fkRegionId == region.Id && w.Type == type && w.ApbnKey == context.Apbn.Key); if (workItem == null) { using (var tx = dbContext.Database.BeginTransaction()) { var typeStr = type.ToString(); typeStr = typeStr.Replace("National", ""); typeStr = typeStr.Replace("Regional", ""); typeStr = typeStr.ToUpper(); var root = HttpContext.Current.Server.MapPath("~/Content/sheets"); Directory.CreateDirectory(root); var safeFileName = typeStr + " " + apbnKey + " " + regionId + " " + region.Name + ".xlsx"; var fullPath = Path.Combine(root, safeFileName); var bytes = adapters[type].GetBytes(context); File.WriteAllBytes(fullPath, bytes); var authEmail = ConfigurationManager.AppSettings["Drive.AuthEmail"]; var authKey = ConfigurationManager.AppSettings["Drive.AuthKey"]; var parentDir = ConfigurationManager.AppSettings["Drive.ParentDir"]; var driveUtils = new DriveUtils(authEmail, authKey, parentDir); var workDir = dbContext.Set <SpreadsheetWorkDir>().FirstOrDefault( d => d.fkUserId == userId); if (workDir == null) { var dirName = string.Format("KawalDesa Sheets - ({0})", userName); workDir = new SpreadsheetWorkDir() { GoogleSheetId = driveUtils.CreateParentDirectory(userEmail, dirName), fkUserId = userId }; dbContext.Set <SpreadsheetWorkDir>().Add(workDir); dbContext.SaveChanges(); } workItem = new SpreadsheetWorkItem() { GoogleSheetId = driveUtils.UploadFile(workDir.GoogleSheetId, fullPath, safeFileName), fkUserId = userId, fkRegionId = region.Id, ApbnKey = apbnKey, Type = type }; dbContext.Set <SpreadsheetWorkItem>().Add(workItem); dbContext.SaveChanges(); tx.Commit(); } } //string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority); //return fullyQualifiedUrl + "/Content/sheets/" + safeFileName; return("https://docs.google.com/spreadsheets/d/" + workItem.GoogleSheetId); }
public void Upload(Multipart <Transfer> multipart, DocumentUploadType type, SourceDocumentFunction fn, string regionId, string apbnKey) { try { KawalDesaController.CheckRegionAllowed(dbContext, regionId); DocumentUploadType t = (DocumentUploadType)type; var region = dbContext.Set <Region>() .Include(r => r.Parent) .Include(r => r.Parent.Parent) .Include(r => r.Parent.Parent.Parent) .Include(r => r.Parent.Parent.Parent.Parent) .First(r => r.Id == regionId); var apbn = dbContext.Set <Apbn>().First(a => a.Key == apbnKey); var user = KawalDesaController.GetCurrentUser(); //if (region.Type != RegionType.NASIONAL && region.Type != RegionType.KABUPATEN) // throw new ApplicationException("only allowed to upload on nasional or kabupaten"); using (var tx = dbContext.Database.BeginTransaction()) { Transfer transfer = multipart.Entity; if (transfer != null) { ModelState.Clear(); Validate(transfer); if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } transfer.IsActivated = true; transfer.fkRegionId = regionId; transfer.Year = Convert.ToInt32(apbnKey.Substring(0, 4)); dbContext.Set <Transfer>().Add(transfer); dbContext.SaveChanges(); dumpMessager.Message("p " + apbnKey + " " + regionId); } if (fn == SourceDocumentFunction.Allocation) { string stype = null; switch (type) { case DocumentUploadType.NationalDd: case DocumentUploadType.RegionalDd: stype = "dd"; break; case DocumentUploadType.NationalAdd: case DocumentUploadType.RegionalAdd: stype = "add"; break; case DocumentUploadType.NationalBhpr: case DocumentUploadType.RegionalBhpr: stype = "bhpr"; break; } if (stype == null) { throw new ApplicationException("invalid doc type: " + type); } dumpMessager.Message(stype + " " + apbnKey + " " + regionId); } foreach (var fileResult in multipart.Files) { var blob = new Blob(fileResult); dbContext.Set <Blob>().Add(blob); dbContext.SaveChanges(); fileResult.Move(blob.FilePath); var doc = new SourceDocument(); doc.ThumbnailCreated = false; doc.FileName = blob.RelativeFileName; doc.fkCreatedById = user.Id; doc.fkOrganizationId = user.fkOrganizationId.Value; doc.DateCreated = DateTime.Now; doc.Type = type; doc.Function = fn; doc.ApbnKey = apbnKey; doc.fkRegionId = regionId; doc.fkFileId = blob.Id; if (transfer != null) { doc.fkTransferId = transfer.Id; } dbContext.Set <SourceDocument>().Add(doc); dbContext.SaveChanges(); } tx.Commit(); } } finally { multipart.DeleteUnmoved(); } }
public void AddTransferTransaction(Multipart <Transaction> multipart) { Validate(multipart.Entity); if (!ModelState.IsValid) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } var context = HttpContext.Current; var principal = HttpContext.Current.User; try { var user = (principal.Identity as KawalDesaIdentity).User; var transaction = multipart.Entity; KawalDesaController.CheckRegionAllowed(principal, dbContext, transaction.fkDestinationId); var actor = dbContext.Set <Region>().First(r => r.Id == transaction.fkActorId); var source = dbContext.Set <Region>().First(r => r.Id == transaction.fkSourceId); var destination = dbContext.Set <Region>().First(r => r.Id == transaction.fkDestinationId); long?accountId = null; if (transaction.fkActorId == transaction.fkDestinationId) { var targetSource = transaction.fkSourceId == "0" ? "apbn" : "add"; //accountId = dbContext.Set<Account>().First(a => a.TargetSource == targetSource && a.Apbdes.fkRegionId == transaction.fkDestinationId).Id; } string roleRequired = null; if (actor.Type == RegionType.NASIONAL || actor.Type == RegionType.KABUPATEN) { roleRequired = Role.VOLUNTEER_TRANSFER; } else if (actor.Type == RegionType.DESA) { if ((source.Type == RegionType.KABUPATEN || source.Type == RegionType.NASIONAL) && destination.Type == RegionType.DESA) { roleRequired = Role.VOLUNTEER_DESA; } } if (roleRequired == null) { throw new ApplicationException(String.Format("No role matched for transaction: {0}, {1}, {2}", actor.Type, source.Type, destination.Type)); } if (!principal.IsInRole(roleRequired)) { throw new ApplicationException("Principal is not in role"); } long?blobId = null; if (multipart.Files.Count > 0) { var fileResult = multipart.Files[0]; var blob = new Blob(fileResult); dbContext.Set <Blob>().Add(blob); dbContext.SaveChanges(); fileResult.Move(blob.FilePath); blobId = blob.Id; } transaction.fkSourceFileId = blobId; transaction.IsActivated = true; transaction.fkCreatedById = user.Id; transaction.fkAccountId = accountId; dbSet.Add(transaction); dbContext.SaveChanges(); } finally { multipart.DeleteUnmoved(); } }
public void AddAccountTransaction(Multipart multipart) { try { if (multipart.GetForm("Amount") != null && long.Parse(multipart.GetForm("Amount")) < 0) { throw new ApplicationException("Amount must be greater than 0"); } if (multipart.GetForm("Description") == null) { throw new ApplicationException("Description cannot be empty"); } Transaction transaction = new Transaction { Amount = long.Parse(multipart.GetForm("Amount")), fkAccountId = long.Parse(multipart.GetForm("fkAccountId")), Date = DateTime.ParseExact(multipart.GetForm("Date"), "dd-MM-yyyy", CultureInfo.InvariantCulture) }; /* * Realization realization = new Realization * { * Description = multipart.GetForm("Description") * }; */ var account = dbContext.Set <Account>() .Include(a => a.Apbdes) .First(a => a.Id == transaction.fkAccountId); KawalDesaController.CheckRegionAllowed(dbContext, account.Apbdes.fkRegionId); transaction.fkActorId = account.Apbdes.fkRegionId; dbContext.Set <Transaction>().Add(transaction); //realization.fkTransactionId = transaction.Id; //dbContext.Set<Realization>().Add(realization); if (multipart.Files.Count > 0) { var fileResult = multipart.Files[0]; var blob = new Blob(fileResult); dbContext.Set <Blob>().Add(blob); /* * TODO * TransactionFile transactionFile = new TransactionFile() * { * FileName = blob.Name, * fkFileId = blob.Id, * IsActivated = true * }; * dbContext.Set<TransactionFile>().Add(transactionFile); */ fileResult.Move(blob.FilePath); } dbContext.SaveChanges(); } finally { multipart.DeleteUnmoved(); } }