Example #1
0
        public async Task FunctionHandler(RoutedPodioEvent e, ILambdaContext context)
        {
            string lockValue;
            var    factory = new AuditedPodioClientFactory(e.solutionId, e.version, e.clientId, e.environmentId);

            podio = factory.ForClient(e.clientId, e.environmentId);
            //context.Logger.LogLine("Getting Podio Instance");
            check = await podio.GetItem(Convert.ToInt32(e.podioEvent.item_id));

            context.Logger.LogLine($"Got item with ID: {check.ItemId}");
            var saasafrasClient = new SaasafrasClient(Environment.GetEnvironmentVariable("BBC_SERVICE_URL"), Environment.GetEnvironmentVariable("BBC_SERVICE_API_KEY"));

            //context.Logger.LogLine("Getting BBC Client Instance");
            dictChild = await saasafrasClient.GetDictionary(e.clientId, e.environmentId, e.solutionId, e.version);

            dictMaster = await saasafrasClient.GetDictionary("vcadministration", "vcadministration", "vilcap", "0.0");

            //context.Logger.LogLine("Got dictionary");
            var functionName = "newVilcapCopyFileToGoogleDrive";

            var serviceAcccount = Environment.GetEnvironmentVariable("GOOGLE_SERVICE_ACCOUNT");
            var cred            = GoogleCredential.FromJson(serviceAcccount).CreateScoped(Scopes).UnderlyingCredential;

            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred,
                ApplicationName       = ApplicationName,
            });
            //context.Logger.LogLine("Established google connection");
            //context.Logger.LogLine($"App: {check.App.Name}");

            google = new GoogleIntegration();
            var saasGoogleIntegration = new SaasafrasGoogleIntegration();

            pre = new PreSurvAndExp();
            ids = new GetIds(dictChild, dictMaster, e.environmentId);
            var comm = new CommentService(podio);
            var s    = new Survey();

            // Main Process //

            var revision = await podio.GetRevisionDifference(Convert.ToInt32(check.ItemId), check.CurrentRevision.Revision - 1, check.CurrentRevision.Revision);

            var firstRevision = revision.First();

            context.Logger.LogLine($"Last Revision field: {firstRevision.Label}");

            var buttonPresser = check.CurrentRevision.CreatedBy;

            //context.Logger.LogLine($"Item updated by {buttonPresser.Name} (Should be 'Vilcap Admin')");
            if (buttonPresser.Id.GetValueOrDefault() != 4610903)
            {
                context.Logger.LogLine("User ' https://podio.com/users/" + buttonPresser.Id + " ' is not authorized to perform this action.");
                return;
            }

            switch (firstRevision.Label)
            {
            case "WS Batch":
                #region     // Create Workshops //
                var wsBatchId = ids.GetFieldId("Admin|WS Batch");
                if (check.Field <CategoryItemField>(wsBatchId).Options.Any())
                {
                    context.Logger.LogLine($"Running 'WS Batch {check.Field<CategoryItemField>(wsBatchId).Options.First().Text}'");
                    var nextBatch = -1;
                    lockValue = await saasafrasClient.LockFunction(functionName, check.ItemId.ToString());

                    try
                    {
                        if (string.IsNullOrEmpty(lockValue))
                        {
                            context.Logger.LogLine($"Failed to acquire lock for {functionName} and id {check.ItemId}");
                            return;
                        }
                        context.Logger.LogLine($"Lock Value: {lockValue}");

                        var wm = new WorkshopModules2();
                        nextBatch = await wm.CreateWorkshopModules2(this);

                        if (nextBatch > 1)
                        {
                            commentText = $"WS Batch {nextBatch - 1} Completed.";
                            check.Field <CategoryItemField>(ids.GetFieldId("Admin|WS Batch")).OptionText = $"{nextBatch}";
                            await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);

                            await comm.AddCommentToObject("item", check.ItemId, commentText, hook : true);

                            //await podio.UpdateItem(check, hook: true);
                            return;
                        }
                        else if (nextBatch == -1)
                        {
                            commentText = $":loudspeaker: All WS Batches Completed!";
                            await comm.AddCommentToObject("item", check.ItemId, commentText, hook : false);
                        }
                    }

                    catch (Exception ex)
                    {
                        context.Logger.LogLine($"Exception Details: {ex} - {ex.Data} - {ex.HelpLink} - {ex.HResult} - {ex.InnerException} " +
                                               $"- {ex.Message} - {ex.Source} - {ex.StackTrace} - {ex.TargetSite}");
                        commentText = "Sorry, something went wrong. Please try again in 5 minutes or contact the administrator.";
                        await comm.AddCommentToObject("item", check.ItemId, $":loudspeaker: {commentText}", hook : false);
                    }

                    finally
                    {
                        await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);
                    }
                }
                break;
                #endregion

            case "Deploy Addons":
                #region     // Deploy Addon Modules //
                var aoBatchId = ids.GetFieldId("Admin|Deploy Addons");
                if (check.Field <CategoryItemField>(aoBatchId).Options.Any())
                {
                    context.Logger.LogLine($"Running 'WS Batch {check.Field<CategoryItemField>(aoBatchId).Options.First().Text}'");
                    var nextBatch = -1;
                    lockValue = await saasafrasClient.LockFunction(functionName, check.ItemId.ToString());

                    try
                    {
                        if (string.IsNullOrEmpty(lockValue))
                        {
                            context.Logger.LogLine($"Failed to acquire lock for {functionName} and id {check.ItemId}");
                            return;
                        }
                        context.Logger.LogLine($"Lock Value: {lockValue}");

                        var ao = new Addons();
                        nextBatch = await ao.CreateAddons(context, podio, check, e, service, ids, google, pre);

                        break;
                    }

                    catch (Exception ex)
                    {
                        context.Logger.LogLine($"Exception Details: {ex} - {ex.Data} - {ex.HelpLink} - {ex.HResult} - {ex.InnerException} " +
                                               $"- {ex.Message} - {ex.Source} - {ex.StackTrace} - {ex.TargetSite}");
                        commentText = "Sorry, something went wrong. Please try again in 5 minutes or contact the administrator.";
                        await comm.AddCommentToObject("item", check.ItemId, $":loudspeaker: {commentText}", hook : false);
                    }

                    finally
                    {
                        await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);
                    }
                }
                break;
                #endregion

            //case "Deploy Task List":
            //    var deploy = ids.GetFieldId("Admin|Deploy Task List");
            //    if (check.Field<CategoryItemField>(deploy).Options.Any());
            //    break;

            case "TL Batch":
                #region     // Create Task List //
                var tlBatchId = ids.GetFieldId("Admin|TL Batch");
                if (check.Field <CategoryItemField>(tlBatchId).Options.Any())
                {
                    context.Logger.LogLine($"Running 'TL Batch {check.Field<CategoryItemField>(tlBatchId).Options.First().Text}'");
                    var nextBatch = -1;
                    lockValue = await saasafrasClient.LockFunction(functionName, check.ItemId.ToString());

                    try
                    {
                        if (string.IsNullOrEmpty(lockValue))
                        {
                            context.Logger.LogLine($"Failed to acquire lock for {functionName} and id {check.ItemId}");
                            return;
                        }
                        context.Logger.LogLine($"Lock Value: {lockValue}");

                        var tl = new TaskList2();
                        nextBatch = await tl.CreateTaskLists(context, podio, check, e, service, ids, google, pre);

                        if (nextBatch > 1)
                        {
                            commentText = $"TL Batch {nextBatch - 1} Completed.";
                            check.Field <CategoryItemField>(ids.GetFieldId("Admin|TL Batch")).OptionText = $"{nextBatch}";
                            await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);

                            await comm.AddCommentToObject("item", check.ItemId, commentText, hook : true);

                            //await podio.UpdateItem(check, hook: true);
                            return;
                        }
                        else if (nextBatch == -1)
                        {
                            commentText = $":loudspeaker: All TL Batches Completed!";
                            await comm.AddCommentToObject("item", check.ItemId, commentText, hook : false);
                        }
                    }
                    catch (Exception ex)
                    {
                        context.Logger.LogLine($"Exception Details: {ex} - {ex.Data} - {ex.HelpLink} - {ex.HResult} - {ex.InnerException} " +
                                               $"- {ex.Message} - {ex.Source} - {ex.StackTrace} - {ex.TargetSite}");
                        commentText = "Sorry, something went wrong. Please try again in 5 minutes or contact the administrator.";
                        await comm.AddCommentToObject("item", check.ItemId, $":loudspeaker: {commentText}", hook : false);
                    }
                    finally
                    {
                        await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);
                    }
                }
                break;
                #endregion

            default:
                context.Logger.LogLine($"NO ACTION: Value '{firstRevision.Label}' not Recognized.");
                break;
            }
        }
Example #2
0
        public async System.Threading.Tasks.Task CreateTaskLists(ILambdaContext context, Podio podio, Item check, RoutedPodioEvent e, DriveService service, GetIds ids, GoogleIntegration google, PreSurvAndExp pre)
        {
            string commentText;
            var    TlStatusId  = ids.GetFieldId("Admin|Hidden Status");
            var    startDateId = ids.GetFieldId("Admin|Program Start Date");
            //var packageId = ids.GetFieldId("Admin|Curriculum Package");
            //string packageName = check.Field<CategoryItemField>(packageId).Options.First().Text;
            var fieldId = 0;

            context.Logger.LogLine("Satisfied conditions, Task List Function");
            var viewServ = new ViewService(podio);

            context.Logger.LogLine("Got View Service");
            var views = await viewServ.GetViews(21310276);            //VC Admin Master Schedule App

            var view = from v in views
                       where v.Name == "Package" // ------------- >> where v.Name == packageName
                       select v;
            //context.Logger.LogLine($"Got View '{packageName}'");
            var op = new FilterOptions {
                Filters = view.First().Filters
            };

            if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "1")
            {
                context.Logger.LogLine("Grabbing items 1-30");
                op.Offset = 0;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 1 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "2")
            {
                context.Logger.LogLine("Grabbing items 31-60");
                op.Offset = 30;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 2 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "3")
            {
                context.Logger.LogLine("Grabbing items 61-90");
                op.Offset = 60;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 3 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "4")
            {
                context.Logger.LogLine("Grabbing items 91-120 with links");
                op.Offset = 90;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 4 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "5")
            {
                context.Logger.LogLine("Grabbing items 121-150 with links");
                op.Offset = 120;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 5 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "6")
            {
                context.Logger.LogLine("Grabbing items 151-180 with links");
                op.Offset = 150;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 6 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "7")
            {
                context.Logger.LogLine("Grabbing items 181-210 with links");
                op.Offset = 180;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 7 finished";
            }
            else if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "8")
            {
                context.Logger.LogLine("Grabbing items 211-240 with links");
                op.Offset = 210;
                op.Limit  = 30;
                filter    = await podio.FilterItems(21310276, op);

                commentText = "Batch 8 finished";
            }
            else
            {
                context.Logger.LogLine("Grabbing nothing --- undefined input");
                commentText = "";
            }
            context.Logger.LogLine($"Items in filter:{filter.Items.Count()}");
            var count = 0;

            foreach (var masterItem in filter.Items)
            {
                count += 1;
                context.Logger.LogLine($"On item #: {count}");
                var child = new Item();


                //--- Assign Fields ---//
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Task Name");
                var nameMaster = masterItem.Field <TextItemField>(fieldId);
                if (nameMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Task List|Title");
                    var nameChild = child.Field <TextItemField>(fieldId);
                    nameChild.Value = nameMaster.Value;
                }
                context.Logger.LogLine($"Added field:{nameMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Desciption");
                var descrMaster = masterItem.Field <TextItemField>(fieldId);
                if (descrMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Task List|Description");
                    var descrChild = child.Field <TextItemField>(fieldId);
                    //descrChild.Value = StripHTML(descrMaster.Value);
                    descrChild.Value = descrMaster.Value;
                }
                context.Logger.LogLine($"Added field:{descrMaster.Label}");

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Phase");
                var phaseMaster = masterItem.Field <CategoryItemField>(fieldId);
                if (phaseMaster.Options.Any())
                {
                    fieldId = ids.GetFieldId("Task List|Phase");
                    var phaseChild = child.Field <CategoryItemField>(fieldId);
                    phaseChild.OptionText = phaseMaster.Options.First().Text;
                    if (phaseMaster.Options.First().Text == "Dependent Task")
                    {
                        continue;
                    }
                }

                context.Logger.LogLine($"Added field:{phaseMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|ESO Member Role");
                var esoMaster = masterItem.Field <CategoryItemField>(fieldId);
                if (esoMaster.Options.Any())
                {
                    fieldId = ids.GetFieldId("Task List|ESO Member Role");
                    var esoChild = child.Field <CategoryItemField>(fieldId);
                    esoChild.OptionText = esoMaster.Options.First().Text;
                }
                context.Logger.LogLine($"Added field:{esoMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Project");
                var projectMaster = masterItem.Field <CategoryItemField>(fieldId);
                if (projectMaster.Options.Any())
                {
                    fieldId = ids.GetFieldId("Task List|Project");
                    var projectChild = child.Field <CategoryItemField>(fieldId);
                    projectChild.OptionText = projectMaster.Options.First().Text;
                }
                context.Logger.LogLine($"Added field:{projectMaster.Label}");

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Base Workshop Association");
                var wsMaster = masterItem.Field <CategoryItemField>(fieldId);
                if (wsMaster.Options.Any())
                {
                    fieldId = ids.GetFieldId("Task List|WS Association");
                    var wsChild = child.Field <TextItemField>(fieldId);
                    wsChild.Value = wsMaster.Options.First().Text;
                    fieldId       = ids.GetFieldId("Task List|Parent WS");
                    var parentChild = child.Field <CategoryItemField>(fieldId);
                    parentChild.OptionText = wsMaster.Options.First().Text;
                }
                context.Logger.LogLine($"Added field:{wsMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Weeks Off-Set");
                var offsetMaster = masterItem.Field <NumericItemField>(fieldId);
                if (offsetMaster.Value.HasValue)
                {
                    fieldId = ids.GetFieldId("Task List|Week Offset");
                    var offsetChild = child.Field <NumericItemField>(fieldId);
                    offsetChild.Value = offsetMaster.Value;
                    fieldId           = ids.GetFieldId("Task List|Weeks Before WS");
                    var weeksChild = child.Field <NumericItemField>(fieldId);
                    weeksChild.Value = offsetMaster.Value;
                }
                context.Logger.LogLine($"Added field:{offsetMaster.Label}");
                fieldId = ids.GetFieldId("Task List|Completetion");
                var comChild = child.Field <CategoryItemField>(fieldId);
                comChild.OptionText = "Incomplete";
                context.Logger.LogLine($"Added field: Completion");

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Duration (Days)");
                var durMaster = masterItem.Field <NumericItemField>(fieldId);
                if (durMaster.Value.HasValue)
                {
                    fieldId = ids.GetFieldId("Task List|Duration (days)");
                    var durChild = child.Field <NumericItemField>(fieldId);
                    durChild.Value = durMaster.Value;
                }
                context.Logger.LogLine($"Added field:{durMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Dependancy");
                var depMaster = masterItem.Field <TextItemField>(fieldId);
                if (depMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Task List|Additional Dependencies");
                    var depChild = child.Field <TextItemField>(fieldId);
                    depChild.Value = depMaster.Value;
                }
                context.Logger.LogLine($"Added field:{depMaster.Label}");
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Gdrive Link");
                var embedMaster = masterItem.Field <EmbedItemField>(fieldId);
                fieldId = ids.GetFieldId("Task List|Linked Files");
                var embedChild     = child.Field <EmbedItemField>(fieldId);
                var embeds         = new List <Embed>();
                var parentFolderId = Environment.GetEnvironmentVariable("GOOGLE_PARENT_FOLDER_ID");
                var cloneFolderId  = google.GetSubfolderId(service, podio, e, parentFolderId);               //TODO:
                foreach (var em in embedMaster.Embeds)
                {
                    if (em.OriginalUrl.Contains(".google."))
                    {
                        await google.UpdateOneEmbed(service, em, embeds, cloneFolderId, podio, e);
                    }
                    //else          // Hold for 2.0 //
                    //{
                    //	NonGdriveLinks nonG = new NonGdriveLinks();
                    //	await nonG.NonGDriveCopy(em, embeds, podio, e);
                    //}
                }
                foreach (var embed in embeds)
                {
                    embedChild.AddEmbed(embed.EmbedId);
                }
                context.Logger.LogLine($"Added field:{embedMaster.Label}");
                var taskListAppId = ids.GetFieldId("Task List");
                var waitSeconds   = 5;
CallPodio:
                try
                {
                    await podio.CreateItem(child, taskListAppId, true);                    //child task list appId
                }
                catch (PodioUnavailableException ex)
                {
                    context.Logger.LogLine($"{ex.Message}");
                    context.Logger.LogLine($"Trying again in {waitSeconds} seconds.");
                    for (var i = 0; i < waitSeconds; i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        context.Logger.LogLine(".");
                    }
                    waitSeconds = waitSeconds * 2;
                    goto CallPodio;
                }
                context.Logger.LogLine($"Created item #{count}");
            }
            var comm = new CommentService(podio);

            if (check.Field <CategoryItemField>(TlStatusId).Options.First().Text == "1")
            {
                await pre.CreateExpendituresAndPreWSSurvs(context, podio, viewServ, check, e, service, ids, google);
            }
            await comm.AddCommentToObject("item", check.ItemId, commentText, hook : true);
        }
Example #3
0
        public async System.Threading.Tasks.Task FunctionHandler(RoutedPodioEvent e, ILambdaContext context)
        {
            var factory = new AuditedPodioClientFactory(e.solutionId, e.version, e.clientId, e.environmentId);
            var podio   = factory.ForClient(e.clientId, e.environmentId);
            var check   = await podio.GetItem(Convert.ToInt32(e.podioEvent.item_id));

            var saasafrasClient = new SaasafrasClient(System.Environment.GetEnvironmentVariable("BBC_SERVICE_URL"), System.Environment.GetEnvironmentVariable("BBC_SERVICE_API_KEY"));
            var dictChild       = await saasafrasClient.GetDictionary(e.clientId, e.environmentId, e.solutionId, e.version);

            var dictMaster = await saasafrasClient.GetDictionary("vcadministration", "vcadministration", "vilcap", "0.0");

            string lockValue;
            var    ids = new GetIds(dictChild, dictMaster, e.environmentId);
            //Make sure to implement by checking to see if Deploy Curriculum has just changed
            //Deploy Curriculum field
            var functionName = "VilcapConfirmAppEmail";

            lockValue = await saasafrasClient.LockFunction(functionName, check.ItemId.ToString());

            try
            {
                if (string.IsNullOrEmpty(lockValue))
                {
                    context.Logger.LogLine($"Failed to acquire lock for {functionName} and id {check.ItemId}");
                    return;
                }
                var revision = await podio.GetRevisionDifference
                               (
                    Convert.ToInt32(check.ItemId),
                    check.CurrentRevision.Revision - 1,
                    check.CurrentRevision.Revision
                               );

                var firstRevision = revision.First();
                var complete      = check.Field <CategoryItemField>(ids.GetFieldId("Applications|Complete This Application"));
                if (firstRevision.FieldId == complete.FieldId)
                {
                    if (complete.Options.Any() && complete.Options.First().Text == "Submit")
                    {
                        var recipient = check.Field <EmailItemField>(ids.GetFieldId("Applications|Email")).Value.First().Value;
                        //get admin item to get program manager name
                        var items = await podio.FilterItems(ids.GetFieldId("Admin"), new FilterOptions()
                        {
                            Limit = 1
                        });

                        var adminItem = await podio.GetItem(items.Items.First().ItemId);

                        var fromName = adminItem.Field <ContactItemField>(ids.GetFieldId("Admin|Program Manager")).Contacts.First().Name;
                        //var subject = "Thank you for submitting your application!";
                        var messageBody = $"Thank you for submitting your application to {ids.GetLongName( $"{e.environmentId}-FN" )}'s Future of Work" +
                                          " and Learning Program 2019. We will be reviewing your application and following up in the " +
                                          "coming weeks regarding next steps. If you do have questions, please feel free to email me at " +
                                          "[[email protected]](mailto: [email protected])";
                        var comm = new CommentService(podio);
                        await comm.AddCommentToObject("item", check.ItemId, messageBody);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                await saasafrasClient.UnlockFunction(functionName, check.ItemId.ToString(), lockValue);
            }
        }