Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        public async System.Threading.Tasks.Task <int> CreateAddons(ILambdaContext context, Podio podio, Item check, RoutedPodioEvent e, DriveService service, GetIds ids, GoogleIntegration google, PreSurvAndExp pre)
        {
            #region // Utility vars //

            const int MASTER_CONTENT_APP = 21310273;

            var commentText   = "";
            var fieldId       = 0;
            var count         = 0;
            var workshopAppId = ids.GetFieldId("Workshop Modules");
            var tasklistAppId = ids.GetFieldId("Task List");
            var waitSeconds   = 5;

            var day           = 0;
            var timeFromStart = new TimeSpan(0);
            #endregion

            #region // Admin app values //

            var startDateId = ids.GetFieldId("Admin|Program Start Date");
            var startDate   = new DateTime(check.Field <DateItemField>(startDateId).Start.Value.Ticks);

            var addonId = ids.GetFieldId("Admin|Addons");
            var addon   = check.Field <CategoryItemField>(addonId).Options.First().Text;

            #endregion

            #region // Get Modules //

            var viewServ = new ViewService(podio);
            context.Logger.LogLine("Got View Service");
            var views = await viewServ.GetViews(MASTER_CONTENT_APP);

            var view = from v in views
                       where v.Name == addon
                       select v;
            context.Logger.LogLine($"Got View '{addon}'");

            var op = new FilterOptions {
                Filters = view.First().Filters
            };
            op.SortBy   = "185391072"; // fieldId of Package Sequence (num) from Content Curation
            op.SortDesc = false;

            context.Logger.LogLine($"Grabbing Items ...");
            filter = await podio.FilterItems(MASTER_CONTENT_APP, op);

            context.Logger.LogLine($"Items in filter:{filter.Items.Count()}");
            commentText = $"Addon Batch finished";

            if (filter.Items.Count() > 0)
            {
                context.Logger.LogLine("WARNING: No items found for batch!");
                commentText = "No items found for this Addon";
            }
            #endregion

            // Main Loop //

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

                #region // Check for new Day //

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Workshop Day");
                var dayMaster = master.Field <CategoryItemField>(fieldId);
                if (dayMaster.Values != null)
                {
                    var dayMasterVal = 0;
                    Int32.TryParse(dayMaster.Options.First().Text.Split("Day ")[1], out dayMasterVal);

                    if ((dayMasterVal != day) && (dayMasterVal != 0))
                    {
                        day           = dayMasterVal;
                        timeFromStart = TimeSpan.FromDays(day - 1);
                    }
                }
                #endregion

                #region // Assign Fields //

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Workshop Detail Title");
                var titleMaster = master.Field <TextItemField>(fieldId);
                if (titleMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Title");
                    var titleChild = child.Field <TextItemField>(fieldId);
                    titleChild.Value = titleMaster.Value;
                }

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Purpose");
                var descMaster = master.Field <TextItemField>(fieldId);
                if (descMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Description");
                    var descChild = child.Field <TextItemField>(fieldId);
                    //descChild.Value = StripHTML(descMaster.Value);
                    descChild.Value = descMaster.Value;
                }

                var offsetMaster = master.Field <NumericItemField>(ids.GetFieldId("VC Administration|Content Curation |Minute Offset"));
                if (offsetMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Minute Offset");
                    var offsetChild = child.Field <NumericItemField>(fieldId);
                    offsetChild.Value = offsetMaster.Value;
                }

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Entrepreneur Pre-Work Required");
                var workMaster = master.Field <TextItemField>(fieldId);
                if (workMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Entrepreneur Pre-work Required");
                    var workChild = child.Field <TextItemField>(fieldId);
                    workChild.Value = workMaster.Value;
                }

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Materials Required");
                var matsMaster = master.Field <TextItemField>(fieldId);
                if (matsMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Additional Materials Required");
                    var matsChild = child.Field <TextItemField>(fieldId);
                    matsChild.Value = matsMaster.Value;
                }

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Mentors Required");
                var mentMaster = master.Field <TextItemField>(fieldId);
                if (mentMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Mentors Required");
                    var mentChild = child.Field <TextItemField>(fieldId);
                    mentChild.Value = mentMaster.Value;
                }

                var color = child.Field <CategoryItemField>(ids.GetFieldId("Workshop Modules|Calendar Color"));
                color.OptionText = "Addon";

                var childTasks  = child.Field <AppItemField>(ids.GetFieldId("Workshop Modules|Dependent Task"));
                var masterTasks = master.Field <AppItemField>(ids.GetFieldId("VC Administration|Content Curation |Dependent Task"));
                var taskOffset  = master.Field <DurationItemField>(ids.GetFieldId("VC Administration|Content Curation |Dependent Task Offset"));
                #endregion

                #region // Date Calcs //

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Package Sequence");
                var seqMaster = master.Field <CategoryItemField>(fieldId);

                fieldId = ids.GetFieldId("VC Administration|Content Curation |Duration");
                var durMaster = master.Field <DurationItemField>(fieldId);

                if (durMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Workshop Modules|Duration");
                    var durChild = child.Field <DurationItemField>(fieldId);
                    durChild.Value = durMaster.Value.Value.Duration(); // durChild.Value.Value.Add(durMaster.Value.Value);? durChild.Value = durMaster.Value;?

                    var childDateTimeStart = startDate.Add(timeFromStart);
                    var childDateTimeEnd   = childDateTimeStart.Add(durChild.Value.Value.Duration());
                    context.Logger.LogLine($"Trying to scheduling for {childDateTimeStart.ToString()} - {childDateTimeEnd.ToString()}");
                    timeFromStart = timeFromStart.Add(durChild.Value.Value.Duration());

                    fieldId = ids.GetFieldId("Workshop Modules|Date");
                    var childTime = child.Field <DateItemField>(fieldId);
                    childTime.Start = childDateTimeStart;
                    childTime.End   = childDateTimeEnd;
                    context.Logger.LogLine($"Scheduled for {childTime.Start.ToString()} - {childTime.End.ToString()}");
                }
                #endregion

                #region // GDrive Integration //

                fieldId = ids.GetFieldId("VC Administration|Content Curation |GDrive File Name");
                var embedMaster = master.Field <EmbedItemField>(fieldId);
                fieldId = ids.GetFieldId("Workshop Modules|Link to Material");
                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}");
                #endregion

                // Dependent Tasks Generation//
                foreach (var masterTask in masterTasks.Items)
                {
                    var masterT = new Item();
                    context.Logger.LogLine("Creating empty master item");
                    masterT = await podio.GetItem(masterTask.ItemId);

                    context.Logger.LogLine("Got master item");
                    var cloneT = new Item();

                    #region // Assign Dep. Task Fields //

                    var nameMasterTValue = masterT.Field <TextItemField>(ids.GetFieldId("VC Administration|Master Schedule|Task Name")).Value;
                    if (nameMasterTValue != null)
                    {
                        var nameCloneT = cloneT.Field <TextItemField>(ids.GetFieldId("Task List|Title"));
                        nameCloneT.Value = nameMasterTValue;
                    }

                    var descrMasterT = masterT.Field <TextItemField>(ids.GetFieldId("VC Administration|Master Schedule|Desciption"));
                    if (descrMasterT.Value != null)
                    {
                        var descrCloneT = cloneT.Field <TextItemField>(ids.GetFieldId("Task List|Description"));
                        //descrCloneT.Value = StripHTML(descrMasterT.Value);
                        descrCloneT.Value = descrMasterT.Value;
                    }

                    var priorityMasterT = masterT.Field <CategoryItemField>(ids.GetFieldId("VC Administration|Master Schedule|Priority"));
                    if (priorityMasterT.Options.Any())
                    {
                        var priorityCloneT = cloneT.Field <CategoryItemField>(ids.GetFieldId("Task List|Priority"));
                        priorityCloneT.OptionText = priorityMasterT.Options.First().Text;
                    }

                    var phaseMasterT = masterT.Field <CategoryItemField>(ids.GetFieldId("VC Administration|Master Schedule|Phase"));
                    if (phaseMasterT.Options.Any())
                    {
                        var phaseCloneT = cloneT.Field <CategoryItemField>(ids.GetFieldId("Task List|Phase"));
                        phaseCloneT.OptionText = phaseMasterT.Options.First().Text;
                    }

                    var esoMasterT = masterT.Field <CategoryItemField>(ids.GetFieldId("VC Administration|Master Schedule|ESO Member Role"));
                    if (esoMasterT.Options.Any())
                    {
                        var esoCloneT = cloneT.Field <CategoryItemField>(ids.GetFieldId("Task List|ESO Member Role"));
                        esoCloneT.OptionText = esoMasterT.Options.First().Text;
                    }

                    var depMasterT = masterT.Field <TextItemField>(ids.GetFieldId("VC Administration|Master Schedule|Dependancy"));
                    if (depMasterT.Value != null)
                    {
                        var depCloneT = cloneT.Field <TextItemField>(ids.GetFieldId("Task List|Additional Dependencies"));
                        depCloneT.Value = depMasterT.Value;
                    }

                    //var comChild = child.Field<CategoryItemField>(ids.GetFieldId("Task List|Completetion"));
                    //comChild.OptionText = "Incomplete";
                    #endregion

                    #region // Dep. Task Date Calcs //

                    var durationMasterT = masterT.Field <NumericItemField>(ids.GetFieldId("VC Administration|Master Schedule|Duration (Days)"));
                    var dateCloneT      = cloneT.Field <DateItemField>(ids.GetFieldId("Task List|Date"));
                    var durationCloneT  = cloneT.Field <DurationItemField>(ids.GetFieldId("Task List|Duration"));

                    if (durationMasterT.Value != null)
                    {
                        durationCloneT.Value = new TimeSpan((int)durationMasterT.Value.GetValueOrDefault(), 0, 0);
                        var taskStart = new DateTime(child.Field <DateItemField>(ids.GetFieldId("Workshop Modules|Date")).Start.Value.Ticks).Subtract(taskOffset.Value.GetValueOrDefault());
                        dateCloneT.Start = taskStart.Date;
                        var taskEnd = new DateTime(taskStart.AddDays(durationMasterT.Value.GetValueOrDefault()).Ticks);
                        dateCloneT.End = taskEnd.Date;
                    }
                    #endregion

                    #region // Dep. Task Gdrive Integration //

                    fieldId = ids.GetFieldId("VC Administration|Master Schedule|Gdrive Link");
                    var embedMasterT = masterT.Field <EmbedItemField>(fieldId);
                    fieldId = ids.GetFieldId("Task List|Linked Files");
                    var embedChildT     = cloneT.Field <EmbedItemField>(fieldId);
                    var embedsT         = new List <Embed>();
                    var parentFolderIdT = Environment.GetEnvironmentVariable("GOOGLE_PARENT_FOLDER_ID");
                    var cloneFolderIdT  = google.GetSubfolderId(service, podio, e, parentFolderId);//TODO:

                    foreach (var em in embedMasterT.Embeds)
                    {
                        if (em.OriginalUrl.Contains(".google."))
                        {
                            await google.UpdateOneEmbed(service, em, embedsT, cloneFolderIdT, podio, e);
                        }
                        //else          // Hold for 2.0 //
                        //{
                        //	NonGdriveLinks nonG = new NonGdriveLinks();
                        //	await nonG.NonGDriveCopy(em, embeds, podio, e);
                        //}
                    }
                    #endregion

                    #region // Create Dep. Task Item //

CallPodioTasks:
                    try
                    {
                        var newTaskId = await podio.CreateItem(cloneT, tasklistAppId, true); //child Task List appId

                        cloneT = await podio.GetFullItem(newTaskId);

                        context.Logger.LogLine($"newTaskId ({newTaskId}) - cloned itemId ({cloneT.ItemId}) - cloned exId ({cloneT.ExternalId})");
                        context.Logger.LogLine($"Created Dependent Task");
                        childTasks.ItemId = cloneT.ItemId;
                        context.Logger.LogLine($"childTasks values: {childTasks.Values.FirstOrDefault().ToString()}");
                    }
                    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 CallPodioTasks;
                    }
                    #endregion
                }

                #region // Create WorkshopModule Podio Item //
                context.Logger.LogLine($"Calling Podio");
CallPodio:
                try
                {
                    context.Logger.LogLine($"Sending CreateItem Request");
                    context.Logger.LogLine($"child.ItemId={child.ItemId} & child.exId={child.ExternalId}");
                    context.Logger.LogLine($"Sending CreateItem Request");
                    await podio.CreateItem(child, workshopAppId, true);

                    context.Logger.LogLine($"CreateItem Request Complete");
                }
                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}");
                #endregion
            }

            // Return the next Batch #, or -1 if all Items have been completed
            if (count == filter.Items.Count())
            {
                return(1);
            }
            return(-1);
        }
Ejemplo n.º 3
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;
            }
        }
Ejemplo n.º 4
0
        public async System.Threading.Tasks.Task <int> CreateTaskLists(ILambdaContext context, Podio podio, Item check, RoutedPodioEvent e, DriveService service, GetIds ids, GoogleIntegration google, PreSurvAndExp pre)
        {
            // Admin/Utility vars //

            const int PARTITIONS          = 5;
            const int LIMIT               = 25;
            const int MAX_BATCHES         = 10;
            const int MASTER_SCHEDULE_APP = 21310276;
            var       batchNum            = -1;

            var    comm = new CommentService(podio);
            string commentText;
            var    count   = 0;
            var    fieldId = 0;
            var    batchId = ids.GetFieldId("Admin|TL Batch");
            var    batch   = check.Field <CategoryItemField>(batchId).Options.First().Text;

            int.TryParse(batch, out batchNum);
            var tlPackageId   = ids.GetFieldId("Admin|Task List Selection");
            var tlPackageName = check.Field <CategoryItemField>(tlPackageId).Options.First().Text;


            // Generate a rough calendar based on dates in the Admin app  //

            var scheduler = new Scheduler(context, podio, check, e, ids, PARTITIONS);

            // Get/Create View //

            var viewServ = new ViewService(podio);

            context.Logger.LogLine("Got View Service ...");
            var views = await viewServ.GetViews(MASTER_SCHEDULE_APP);

            var view = from v in views
                       where v.Name == tlPackageName
                       select v;

            if (view.Any())
            {
                context.Logger.LogLine($"Got View '{tlPackageName}' ...");
            }
            else
            {
                context.Logger.LogLine($"Creating View '{tlPackageName}' ...");
                var viewReq = new ViewCreateUpdateRequest
                {
                    Name    = $"AWS - {tlPackageName}",
                    SortBy  = "174999400", // fieldId of "Title"
                    Filters = new Dictionary <string, object>
                    {
                        { "185003953" /*Curriculum Package field*/, tlPackageName }
                    }
                };
                var viewId = await viewServ.CreateView(MASTER_SCHEDULE_APP, viewReq);

                view = from v in views
                       where v.Name == viewReq.Name
                       select v;
                context.Logger.LogLine($"Got new View '{viewReq.Name}' ...");
            }

            var op = new FilterOptions {
                Filters = view.First().Filters
            };

            op.Limit = LIMIT;

            // Get Batch //

            if (0 <= batchNum && batchNum <= MAX_BATCHES)
            {
                op.Offset = op.Limit * (batchNum - 1);
                context.Logger.LogLine($"Grabbing Items {op.Offset.Value + 1}-{op.Offset.Value + LIMIT} ...");
                filter = await podio.FilterItems(MASTER_SCHEDULE_APP, op);

                context.Logger.LogLine($"Items in filter:{filter.Items.Count()}");
                commentText = $"TL Batch {batch} finished.";
            }
            else
            {
                context.Logger.LogLine("WARNING: No items found for batch!");
                commentText = "TL Batch # not recognized.";
            }

            // Main Loop //

            foreach (var master in filter.Items)
            {
                // Setup //

                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 = master.Field <TextItemField>(fieldId);
                if (nameMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Task List|Title");
                    var nameChild = child.Field <TextItemField>(fieldId);
                    nameChild.Value = nameMaster.Value;
                }

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Desciption");
                var descrMaster = master.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;
                }

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Phase");
                var phaseMaster = master.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;
                }

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|ESO Member Role");
                var esoMaster = master.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;
                }

                fieldId = ids.GetFieldId("Task List|Completetion");
                var comChild = child.Field <CategoryItemField>(fieldId);
                comChild.OptionText = "Incomplete";

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Dependancy");
                var depMaster = master.Field <TextItemField>(fieldId);
                if (depMaster.Value != null)
                {
                    fieldId = ids.GetFieldId("Task List|Additional Dependencies");
                    var depChild = child.Field <TextItemField>(fieldId);
                    depChild.Value = depMaster.Value;
                }

                // Date Calcs //

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Duration (Days)");
                var durMaster = master.Field <NumericItemField>(fieldId).Value.GetValueOrDefault(0.0);
                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Assignment Group");
                var assignment = master.Field <CategoryItemField>(fieldId);

                if (!assignment.Options.Any())
                {
                    continue;
                }
                Int32.TryParse(assignment.Options.First().Text, out var assignmentVal);
                child = scheduler.SetDate(child, ids, phaseMaster.Options.First().Text, assignmentVal, durMaster);

                // GDrive Integration //

                fieldId = ids.GetFieldId("VC Administration|Master Schedule|Gdrive Link");
                var embedMaster = master.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} ...");
                }

                // Child Item Creation //

                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($"EXCEPTION '{ex.Message}'! Trying again in {waitSeconds} seconds ...");
                    for (var i = 0; i < waitSeconds; i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        context.Logger.LogLine(".");
                    }
                    waitSeconds *= 2;
                    goto CallPodio;
                }
                context.Logger.LogLine($"... Created item #{count}");
            }

            // Update Admin Item for next Batch //


            if (count == LIMIT)
            {
                return(++batchNum);
                //check.Field<CategoryItemField>(ids.GetFieldId("Admin|TL Batch")).OptionText = $"{ batchNum }";
                //await podio.UpdateItem(check, hook: true);
                //ItemService iserv = new ItemService(podio);
                //await iserv.UpdateItem(check);
            }
            else
            {
                commentText += " All Tasklist items added!";
                return(-1);
            }
        }