Skip to content

Commit

Permalink
feat: toteuta testaukseen tapa siirtää nähtävilläolokuulutuksen päätt…
Browse files Browse the repository at this point in the history
…ymisaika välittömästi menneisyyteen (#317)
  • Loading branch information
haapamakim committed Aug 18, 2022
1 parent a90a44e commit 13b716f
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 32 deletions.
2 changes: 1 addition & 1 deletion backend/src/database/dynamoDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let client: DynamoDB.DocumentClient;

function getDynamoDBDocumentClient(): DynamoDB.DocumentClient {
if (!client) {
client = new DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });
client = new DynamoDB.DocumentClient({ apiVersion: "2012-08-10", region: "eu-west-1" });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
AWSXRay.captureAWSClient((client as any).service); // NOSONAR
}
Expand Down
65 changes: 35 additions & 30 deletions backend/src/database/projektiDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async function createProjekti(projekti: DBProjekti): Promise<DocumentClient.PutI
return getDynamoDBDocumentClient().put(params).promise();
}

async function scanProjektit(startKey?: string): Promise<{ startKey: string; projektis: DBProjekti[] }> {
async function scanProjektit(startKey?: string): Promise<{ startKey: string | undefined; projektis: DBProjekti[] }> {
try {
const params: DocumentClient.ScanInput = {
TableName: projektiTableName,
Expand Down Expand Up @@ -68,7 +68,7 @@ async function loadProjektiByOid(oid: string, stronglyConsistentRead = true): Pr
projekti.oid = oid;
return projekti;
} catch (e) {
if (e.code === "ResourceNotFoundException") {
if ((e as { code: string }).code === "ResourceNotFoundException") {
log.warn("projektia ei löydy", { oid });
return undefined;
}
Expand Down Expand Up @@ -97,16 +97,16 @@ async function saveProjekti(dbProjekti: Partial<DBProjekti>): Promise<DocumentCl
}
const setExpression: string[] = [];
const removeExpression: string[] = [];
const ExpressionAttributeNames = {};
const ExpressionAttributeValues = {};
const ExpressionAttributeNames: DocumentClient.ExpressionAttributeNameMap = {};
const ExpressionAttributeValues: DocumentClient.ExpressionAttributeValueMap = {};

dbProjekti.paivitetty = dayjs().format();

for (const property in dbProjekti) {
if (skipAutomaticUpdateFields.indexOf(property) >= 0) {
continue;
}
const value = dbProjekti[property];
const value = dbProjekti[property as keyof DBProjekti];
if (value === undefined) {
continue;
}
Expand Down Expand Up @@ -220,7 +220,7 @@ function insertJulkaisuToList(oid: string, listFieldName: string, julkaisu: unkn
async function deleteJulkaisuFromList(
oid: string,
listFieldName: string,
julkaisut: JulkaisuWithId[],
julkaisut: JulkaisuWithId[] | undefined | null,
julkaisuIdToDelete: number,
description: string
) {
Expand Down Expand Up @@ -252,7 +252,7 @@ type JulkaisuWithId = { id: number } & unknown;
async function updateJulkaisuToList(
oid: string,
listFieldName: string,
julkaisut: JulkaisuWithId[],
julkaisut: JulkaisuWithId[] | undefined | null,
julkaisu: JulkaisuWithId,
description: string
) {
Expand Down Expand Up @@ -355,33 +355,35 @@ export const projektiDatabase = {
await getDynamoDBDocumentClient().update(params).promise();
},

async markFeedbackIsBeingHandled(projekti: DBProjekti, id: string): Promise<string> {
const oid = projekti.oid;
log.info("markFeedbackIsBeingHandled", { oid, id });
const palauteIndex = projekti.palautteet.findIndex((value) => value.id === id);
if (palauteIndex < 0) {
throw new NotFoundError("Palautetta ei löydy: " + oid + " " + id);
async markFeedbackIsBeingHandled(projekti: DBProjekti, id: string): Promise<string | undefined> {
if (projekti.palautteet) {
const oid = projekti.oid;
log.info("markFeedbackIsBeingHandled", { oid, id });
const palauteIndex = projekti.palautteet.findIndex((value) => value.id === id);
if (palauteIndex < 0) {
throw new NotFoundError("Palautetta ei löydy: " + oid + " " + id);
}
const params = {
TableName: projektiTableName,
Key: {
oid,
},
UpdateExpression: "SET #palautteet[" + palauteIndex + "].otettuKasittelyyn = :flag",
ExpressionAttributeNames: {
"#palautteet": "palautteet",
},
ExpressionAttributeValues: {
":flag": true,
},
};
log.info("markFeedbackIsBeingHandled", { params });
await getDynamoDBDocumentClient().update(params).promise();
return id;
}
const params = {
TableName: projektiTableName,
Key: {
oid,
},
UpdateExpression: "SET #palautteet[" + palauteIndex + "].otettuKasittelyyn = :flag",
ExpressionAttributeNames: {
"#palautteet": "palautteet",
},
ExpressionAttributeValues: {
":flag": true,
},
};
log.info("markFeedbackIsBeingHandled", { params });
await getDynamoDBDocumentClient().update(params).promise();
return id;
},

async findProjektiOidsWithNewFeedback(): Promise<string[]> {
const result = [];
const result: string[] = [];

try {
let lastEvaluatedKey = undefined;
Expand All @@ -393,6 +395,9 @@ export const projektiDatabase = {
ExclusiveStartKey: lastEvaluatedKey,
};
const data: DocumentClient.ScanOutput = await getDynamoDBDocumentClient().scan(params).promise();
if (!data?.Items) {
break;
}
data.Items.forEach((item) => result.push(item.oid));
lastEvaluatedKey = data.LastEvaluatedKey;
} while (lastEvaluatedKey);
Expand Down
5 changes: 4 additions & 1 deletion deployment/bin/hassu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ async function main() {
console.log("Deployment of HassuBackendStack failed:", e);
process.exit(1);
});
const hassuFrontendStack = new HassuFrontendStack(app, { internalBucket: hassuDatabaseStack.internalBucket });
const hassuFrontendStack = new HassuFrontendStack(app, {
internalBucket: hassuDatabaseStack.internalBucket,
projektiTable: hassuDatabaseStack.projektiTable,
});
await hassuFrontendStack.process().catch((e) => {
console.log("Deployment of HassuFrontendStack failed:", e);
process.exit(1);
Expand Down
1 change: 1 addition & 0 deletions deployment/bin/setupEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ async function main() {
SONARQUBE_HOST_URL: variables.SonarQubeHostURL,
SONARQUBE_ACCESS_TOKEN: variables.SonarQubeAccessToken,
SEARCH_DOMAIN: searchStackOutputs.SearchDomainEndpointOutput,
TABLE_PROJEKTI: Config.projektiTableName
});

const testUsers = await readParametersByPath("/testusers/", Region.EU_WEST_1);
Expand Down
7 changes: 7 additions & 0 deletions deployment/lib/hassu-frontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
} from "../bin/setupEnvironment";
import { IOriginAccessIdentity } from "@aws-cdk/aws-cloudfront/lib/origin-access-identity";
import { getOpenSearchDomain } from "./common";
import { Table } from "@aws-cdk/aws-dynamodb";

// These should correspond to CfnOutputs produced by this stack
export type FrontendStackOutputs = {
Expand All @@ -53,6 +54,7 @@ export type FrontendStackOutputs = {

interface HassuFrontendStackProps {
internalBucket: Bucket;
projektiTable: Table;
}

export class HassuFrontendStack extends cdk.Stack {
Expand Down Expand Up @@ -93,6 +95,7 @@ export class HassuFrontendStack extends cdk.Stack {
env: {
FRONTEND_DOMAIN_NAME: config.frontendDomainName,
REACT_APP_API_KEY: this.appSyncAPIKey,
TABLE_PROJEKTI: Config.projektiTableName
},
}).build();

Expand Down Expand Up @@ -164,6 +167,10 @@ export class HassuFrontendStack extends cdk.Stack {
const searchDomain = await getOpenSearchDomain(this, accountStackOutputs);
if (nextJSLambdaEdge.nextApiLambda) {
searchDomain.grantIndexReadWrite("projekti-" + Config.env + "-*", nextJSLambdaEdge.nextApiLambda);
if (env !== "prod") {
const projektiTable = this.props.projektiTable;
projektiTable.grantReadWriteData(nextJSLambdaEdge.nextApiLambda);
}
}

const distribution: cloudfront.Distribution = nextJSLambdaEdge.distribution;
Expand Down
10 changes: 10 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ module.exports = (phase) => {
let config = {
reactStrictMode: true,
// trailingSlash: true,

// .dev.ts, .dev.tsx", .dev.js, and .dev.jsx are only available in non-prod environments
pageExtensions: ["ts", "tsx", "js", "jsx"]
.map((extension) => {
const isDevServer = BaseConfig.env !== "prod";
const prodExtension = `(?<!dev\.)${extension}`;
const devExtension = `dev\.${extension}`;
return isDevServer ? [devExtension, extension] : prodExtension;
})
.flat(),
};
if (phase === PHASE_DEVELOPMENT_SERVER) {
config = setupLocalDevelopmentMode(config, env);
Expand Down
36 changes: 36 additions & 0 deletions src/pages/api/test/[oid]/nahtavillaolomenneisyyteen.dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextApiRequest, NextApiResponse } from "next";
import { projektiDatabase } from "../../../../../backend/src/database/projektiDatabase";
import { validateCredentials } from "../../../../util/basicAuthentication";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
let environment = process.env.ENVIRONMENT;
if ((environment == "dev" || environment == "test") && !(await validateCredentials(req.headers.authorization))) {
res.status(401);
res.setHeader("www-authenticate", "Basic");

res.send("");
return;
}

const oid = req.query["oid"];
if (oid instanceof Array || !oid || oid.length == 0) {
res.status(400);
res.send("");
return;
}

res.setHeader("Content-Type", "text/plain; charset=UTF-8");

let dbProjekti = await projektiDatabase.loadProjektiByOid(oid);
if (!dbProjekti) {
res.send("Projektia ei löydy");
return;
}
if (dbProjekti?.nahtavillaoloVaiheJulkaisut) {
for (const julkaisu of dbProjekti.nahtavillaoloVaiheJulkaisut) {
julkaisu.kuulutusVaihePaattyyPaiva = "2022-01-01";
await projektiDatabase.updateNahtavillaoloVaiheJulkaisu(dbProjekti, julkaisu);
}
}
res.send("OK");
}

0 comments on commit 13b716f

Please sign in to comment.