Skip to content

Commit a971a1a

Browse files
committed
Adding changes to save the google sheet id and create the correct columns.
1 parent 14f6150 commit a971a1a

File tree

10 files changed

+158
-18
lines changed

10 files changed

+158
-18
lines changed

eFormAPI/Plugins/TimePlanning.Pn/TimePlanning.Pn/Infrastructure/Helpers/GoogleSheetHelper.cs

Lines changed: 61 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22
using System.Collections.Generic;
33
using System.Linq;
44
using System.Threading.Tasks;
5+
using eFormCore;
56
using Google.Apis.Auth.OAuth2;
67
using Google.Apis.Services;
78
using Google.Apis.Sheets.v4;
89
using Google.Apis.Sheets.v4.Data;
910
using Microsoft.EntityFrameworkCore;
1011
using Microsoft.Extensions.Logging;
12+
using Microting.eForm;
1113
using Microting.eForm.Infrastructure.Constants;
1214
using Microting.eFormApi.BasePn.Abstractions;
1315
using Microting.eFormApi.BasePn.Infrastructure.Helpers.PluginDbOptions;
@@ -18,8 +20,8 @@ namespace TimePlanning.Pn.Infrastructure.Helpers;
1820

1921
public class GoogleSheetHelper
2022
{
21-
public static async Task PushToGoogleSheet(IPluginDbOptions<TimePlanningBaseSettings> options,
22-
IEFormCoreService coreHelper, TimePlanningPnDbContext dbContext, ILogger logger)
23+
public static async Task PushToGoogleSheet(string googleSheetId,
24+
Core core, TimePlanningPnDbContext dbContext, ILogger logger)
2325
{
2426
var privateKeyId = Environment.GetEnvironmentVariable("PRIVATE_KEY_ID");
2527
if (string.IsNullOrEmpty(privateKeyId))
@@ -28,10 +30,9 @@ public static async Task PushToGoogleSheet(IPluginDbOptions<TimePlanningBaseSett
2830
}
2931

3032
var applicationName = "Google Sheets API Integration";
31-
var spreadsheetId = options.Value.GoogleSheetId;
3233
var sheetName = "PlanTimer";
3334

34-
var core = await coreHelper.GetCore();
35+
//var core = await coreHelper.GetCore();
3536
await using var sdkDbContext = core.DbContextHelper.GetDbContext();
3637

3738
var privateKey = Environment.GetEnvironmentVariable("PRIVATE_KEY"); // Replace with your private key
@@ -66,7 +67,7 @@ public static async Task PushToGoogleSheet(IPluginDbOptions<TimePlanningBaseSett
6667

6768
try
6869
{
69-
var headerRequest = service.Spreadsheets.Values.Get(spreadsheetId, $"{sheetName}!A1:1");
70+
var headerRequest = service.Spreadsheets.Values.Get(googleSheetId, $"{sheetName}!A1:1");
7071
var headerResponse = await headerRequest.ExecuteAsync();
7172
var existingHeaders = headerResponse.Values?.FirstOrDefault() ?? new List<object>();
7273

@@ -111,17 +112,36 @@ public static async Task PushToGoogleSheet(IPluginDbOptions<TimePlanningBaseSett
111112
Values = new List<IList<object>> { newHeaders.Cast<object>().ToList() }
112113
};
113114
var updateHeaderRequest =
114-
service.Spreadsheets.Values.Update(updateRequest, spreadsheetId, $"{sheetName}!A1:{columnLetter}1");
115+
service.Spreadsheets.Values.Update(updateRequest, googleSheetId, $"{sheetName}!A1:{columnLetter}1");
115116
updateHeaderRequest.ValueInputOption =
116117
SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
117118
await updateHeaderRequest.ExecuteAsync();
118119

119120
logger.LogInformation("Headers updated successfully.");
120121
}
121122

122-
AutoAdjustColumnWidths(service, spreadsheetId, sheetName, logger);
123+
AutoAdjustColumnWidths(service, googleSheetId, sheetName, logger);
123124

124-
SetAlternatingColumnColors(service, spreadsheetId, 0, newHeaders.Count, logger);
125+
try
126+
{
127+
// ... existing code ...
128+
129+
var sheet = service.Spreadsheets.Get(googleSheetId).Execute().Sheets
130+
.FirstOrDefault(s => s.Properties.Title == sheetName);
131+
if (sheet == null) throw new Exception($"Sheet '{sheetName}' not found.");
132+
133+
var sheetId = sheet.Properties.SheetId;
134+
135+
// ... existing code ...
136+
137+
SetAlternatingColumnColors(service, googleSheetId, sheetId!.Value, newHeaders.Count, logger);
138+
139+
logger.LogInformation("Headers are already up-to-date.");
140+
}
141+
catch (Exception ex)
142+
{
143+
logger.LogError($"An error occurred: {ex.Message}");
144+
}
125145

126146
logger.LogInformation("Headers are already up-to-date.");
127147
}
@@ -183,17 +203,19 @@ private static string GetColumnLetter(int columnIndex)
183203
return columnLetter;
184204
}
185205

186-
static void SetAlternatingColumnColors(SheetsService service, string spreadsheetId, int sheetId, int columnCount, ILogger logger)
206+
static void SetAlternatingColumnColors(SheetsService service, string spreadsheetId, int sheetId, int columnCount,
207+
ILogger logger)
187208
{
188209
var requests = new List<Request>();
189210

190-
for (int i = 3; i < columnCount; i++) // Start from column D (index 3)
211+
for (int i = 3; i < columnCount; i += 2) // Start from column D (index 3) and increment by 2
191212
{
192-
var color = (i % 2 == 0)
193-
? new Color { Red = 1, Green = 1, Blue = 1 }
194-
: new Color { Red = 0.9f, Green = 0.9f, Blue = 0.9f };
213+
var color1 = new Color { Red = 1, Green = 1, Blue = 1 };
214+
var color2 = new Color { Red = 0.9f, Green = 0.9f, Blue = 0.9f };
215+
216+
var color = ((i / 2) % 2 == 0) ? color1 : color2;
195217

196-
var updateCellsRequest = new Request
218+
var updateCellsRequest1 = new Request
197219
{
198220
RepeatCell = new RepeatCellRequest
199221
{
@@ -214,7 +236,29 @@ static void SetAlternatingColumnColors(SheetsService service, string spreadsheet
214236
}
215237
};
216238

217-
requests.Add(updateCellsRequest);
239+
var updateCellsRequest2 = new Request
240+
{
241+
RepeatCell = new RepeatCellRequest
242+
{
243+
Range = new GridRange
244+
{
245+
SheetId = sheetId,
246+
StartColumnIndex = i + 1,
247+
EndColumnIndex = i + 2
248+
},
249+
Cell = new CellData
250+
{
251+
UserEnteredFormat = new CellFormat
252+
{
253+
BackgroundColor = color
254+
}
255+
},
256+
Fields = "userEnteredFormat.backgroundColor"
257+
}
258+
};
259+
260+
requests.Add(updateCellsRequest1);
261+
requests.Add(updateCellsRequest2);
218262
}
219263

220264
var batchUpdateRequest = new BatchUpdateSpreadsheetRequest
@@ -226,4 +270,6 @@ static void SetAlternatingColumnColors(SheetsService service, string spreadsheet
226270

227271
logger.LogInformation("Alternating column colors set successfully.");
228272
}
273+
274+
229275
}

eFormAPI/Plugins/TimePlanning.Pn/TimePlanning.Pn/Services/TimePlanningSettingService/TimeSettingService.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@ public async Task<OperationResult> UpdateSettings(TimePlanningSettingsModel time
9797
{
9898
try
9999
{
100+
// check if the google sheets id is the entire url with gid or anything else than the id, if so, extract the id
101+
if (timePlanningSettingsModel.GoogleSheetId.Contains("https://docs.google.com/spreadsheets/d/"))
102+
{
103+
var split = timePlanningSettingsModel.GoogleSheetId.Split("/");
104+
timePlanningSettingsModel.GoogleSheetId = split[5];
105+
}
106+
100107
await _options.UpdateDb(settings =>
101108
{
102109
settings.GoogleApiKey = timePlanningSettingsModel.GoogleApiKey;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './settings/time-planning-settings/time-planning-settings.component';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<eform-new-subheader [forceStaticTitle]="true" [title]="'Time planning settings' | translate"></eform-new-subheader>
2+
3+
<div class="d-flex flex-column">
4+
<div class="flex-cards">
5+
<mat-card class="mat-card-50">
6+
<mat-card-header class="d-flex">
7+
<h4 class="mat-card-title">Google sheet information</h4>
8+
</mat-card-header>
9+
<mat-card-content>
10+
<div class="row">
11+
<div class="col-12">
12+
<mat-form-field class="w-100">
13+
<input matInput placeholder="Google sheet id" [(ngModel)]="settingsModel.googleSheetId">
14+
</mat-form-field>
15+
</div>
16+
<div class="col-12">
17+
<button mat-raised-button color="primary" (click)="updateGoogleSheetSettings()">Update</button>
18+
</div>
19+
</div>
20+
</mat-card-content>
21+
</mat-card>
22+
</div>
23+
</div>

eform-client/src/app/plugins/modules/time-planning-pn/components/settings/time-planning-settings/time-planning-settings.component.scss

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import {Component, OnDestroy, OnInit} from '@angular/core';
2+
import {Subscription} from 'rxjs';
3+
import {TimePlanningPnSettingsService} from '../../../services';
4+
import {TimePlanningSettingsModel} from '../../../models';
5+
6+
@Component({
7+
selector: 'app-time-planning-settings',
8+
templateUrl: './time-planning-settings.component.html',
9+
styleUrls: ['./time-planning-settings.component.scss']
10+
})
11+
export class TimePlanningSettingsComponent implements OnInit, OnDestroy {
12+
getSettings$: Subscription;
13+
settingsModel: TimePlanningSettingsModel = new TimePlanningSettingsModel();
14+
15+
constructor(private timePlanningPnSettingsService: TimePlanningPnSettingsService) {
16+
}
17+
ngOnInit() {
18+
this.getSettings();
19+
}
20+
21+
ngOnDestroy() {
22+
}
23+
24+
getSettings() {
25+
this.getSettings$ = this.timePlanningPnSettingsService.getAllSettings().subscribe((data) => {
26+
if (data && data.success) {
27+
this.settingsModel = data.model;
28+
}
29+
});
30+
}
31+
32+
updateGoogleSheetSettings() {
33+
this.timePlanningPnSettingsService.updateSettings(this.settingsModel).subscribe((data) => {
34+
if (data && data.success) {
35+
this.getSettings();
36+
}
37+
});
38+
}
39+
}
Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
export class TimePlanningSettingsModel {
2-
folderId?: number;
3-
eformId?: number;
4-
assignedSites: number[] = [];
2+
googleApiKey?: string;
3+
googleSheetId?: string;
54
}

eform-client/src/app/plugins/modules/time-planning-pn/services/time-planning-pn-settings.service.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ export class TimePlanningPnSettingsService {
2323
return this.apiBaseService.get(TimePlanningSettingsMethods.Settings);
2424
}
2525

26+
updateSettings(model: TimePlanningSettingsModel): Observable<OperationResult> {
27+
return this.apiBaseService.put(
28+
TimePlanningSettingsMethods.Settings,
29+
model
30+
);
31+
}
32+
2633
getAvailableSites(): Observable<OperationDataResult<SiteDto[]>> {
2734
return this.apiBaseService.get(TimePlanningSettingsMethods.SettingsSites);
2835
}

eform-client/src/app/plugins/modules/time-planning-pn/time-planning-pn.module.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ import {
1717
TimePlanningPnPlanningsService, TimePlanningPnRegistrationDevicesService,
1818
TimePlanningPnSettingsService,
1919
} from './services';
20+
import {TimePlanningSettingsComponent} from './components';
21+
import {MatCard, MatCardContent, MatCardHeader} from "@angular/material/card";
22+
import {MatFormField} from "@angular/material/form-field";
23+
import {MatInput} from "@angular/material/input";
24+
import {MatButton} from "@angular/material/button";
2025

2126
@NgModule({
2227
imports: [
@@ -28,9 +33,16 @@ import {
2833
RouterModule,
2934
TimePlanningPnRouting,
3035
ReactiveFormsModule,
36+
MatCardHeader,
37+
MatCard,
38+
MatCardContent,
39+
MatFormField,
40+
MatInput,
41+
MatButton,
3142
],
3243
declarations: [
3344
TimePlanningPnLayoutComponent,
45+
TimePlanningSettingsComponent
3446
// TimePlanningTableRowComponent,
3547
// TimePlanningsTableComponent,
3648
// TimePlanningsContainerComponent,

eform-client/src/app/plugins/modules/time-planning-pn/time-planning-pn.routing.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { RouterModule, Routes } from '@angular/router';
33
import { AuthGuard, PermissionGuard } from 'src/app/common/guards';
44
import { TimePlanningPnClaims } from './enums';
55
import { TimePlanningPnLayoutComponent } from './layouts';
6+
import {TimePlanningSettingsComponent} from './components';
67

78
export const routes: Routes = [
89
{
@@ -45,6 +46,11 @@ export const routes: Routes = [
4546
(m) => m.RegistrationDevicesModule
4647
),
4748
},
49+
{
50+
path: 'settings',
51+
canActivate: [AuthGuard],
52+
component: TimePlanningSettingsComponent,
53+
}
4854
],
4955
},
5056
];

0 commit comments

Comments
 (0)