Skip to content

Commit 2b3782a

Browse files
Merge pull request #80 from natalialuzuriaga/main
Schemas: Created new pages for each agency form
2 parents 2480be4 + ec6fdb5 commit 2b3782a

File tree

5 files changed

+427
-123
lines changed

5 files changed

+427
-123
lines changed

404.html

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<!DOCTYPE html>
2+
<html>
3+
4+
<head>
5+
<meta http-equiv="refresh" content="0; url=/?page=">
6+
<script>
7+
// Extract the path from URL (e.g., /cms) and redirect
8+
(function () {
9+
const repoName = "codejson-generator"; // change if needed
10+
const pages = ["gov", "cms"];
11+
const path = window.location.pathname.replace(`/${repoName}`, "").replace(/^\/+/, "").replace(/\/$/, "");
12+
const redirectPage = pages.includes(path);
13+
if (redirectPage) {
14+
var newUrl = `/${repoName ? repoName + "/" : ""}?page=${encodeURIComponent(path)}`;
15+
window.location.replace(newUrl);
16+
}
17+
})();
18+
</script>
19+
</head>
20+
21+
<body>
22+
<p>Page not found.</p>
23+
</body>
24+
25+
</html>

js/formDataToJson.js

Lines changed: 72 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,23 @@ async function retrieveFile(filePath) {
1616

1717
function isMultiSelect(obj) {
1818
for (const key in obj) {
19-
if (typeof obj[key] !== 'boolean') {
20-
return false;
21-
}
19+
if (typeof obj[key] !== 'boolean') {
20+
return false;
21+
}
2222
}
2323
return true; // Returns true if all values are booleans
2424
}
2525

2626
// Convert from dictionary to array
2727
function getSelectedOptions(options) {
28-
let selectedOptions = [];
29-
30-
for (let key in options) {
31-
if(options[key]) {
32-
selectedOptions.push(key);
33-
}
34-
}
35-
return selectedOptions;
28+
let selectedOptions = [];
29+
30+
for (let key in options) {
31+
if (options[key]) {
32+
selectedOptions.push(key);
33+
}
34+
}
35+
return selectedOptions;
3636
}
3737

3838
// Populates fields with form data
@@ -46,7 +46,7 @@ function populateObject(data, schema) {
4646
let value = data[key];
4747

4848
// Adjusts value accordingly if multi-select field
49-
if((typeof value === "object" && isMultiSelect(value))) {
49+
if ((typeof value === "object" && isMultiSelect(value))) {
5050
value = getSelectedOptions(value);
5151
}
5252

@@ -57,7 +57,10 @@ function populateObject(data, schema) {
5757
}
5858

5959
async function populateCodeJson(data) {
60-
const filePath = "schemas/schema.json";
60+
// Fetching schema based on search params
61+
const params = new URLSearchParams(window.location.search);
62+
const page = params.get("page") || "gov";
63+
const filePath = `schemas/${page}/schema.json`;
6164

6265
// Retrieves schema with fields in correct order
6366
const schema = await retrieveFile(filePath);
@@ -87,37 +90,33 @@ async function createCodeJson(data) {
8790
}
8891

8992
// Copies code.json to clipboard
90-
async function copyToClipboard(event){
93+
async function copyToClipboard(event) {
9194
event.preventDefault();
9295

9396
var textArea = document.getElementById("json-result");
94-
textArea.select();
97+
textArea.select();
9598
document.execCommand("copy")
9699
}
97100

98101
const NEW_BRANCH = 'code-json-branch' + Math.random().toString(36).substring(2, 10);
99102

100-
function getOrgAndRepoArgsGitHub(url)
101-
{
103+
function getOrgAndRepoArgsGitHub(url) {
102104
const pattern = /https:\/\/github\.com\/([^\/]+)\/([^\/]+)/;
103-
const match = url.match(pattern);
105+
const match = url.match(pattern);
104106

105-
if(match)
106-
{
107+
if (match) {
107108
const owner = match[1];
108109
const repo = match[2];
109-
return {owner,repo};
110+
return { owner, repo };
110111
}
111-
else
112-
{
112+
else {
113113
throw new Error('Invalid URL!');
114114
}
115115
}
116116

117117

118-
async function createBranchOnProject(projectURL, token)
119-
{
120-
const {owner, repo} = getOrgAndRepoArgsGitHub(projectURL);
118+
async function createBranchOnProject(projectURL, token) {
119+
const { owner, repo } = getOrgAndRepoArgsGitHub(projectURL);
121120

122121
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/git/refs/heads/main`,
123122
{
@@ -130,58 +129,53 @@ async function createBranchOnProject(projectURL, token)
130129

131130
const data = await response.json();
132131

133-
if (response.ok)
134-
{
132+
if (response.ok) {
135133
const sha = data.object.sha;
136-
134+
137135
const createBranchApiUrl = `https://api.github.com/repos/${owner}/${repo}/git/refs`;
138136

139137
// Create the new branch from the base branch
140138
const newBranchResponse = await fetch(createBranchApiUrl, {
141139
method: 'POST',
142140
headers: {
143-
'Content-Type': 'application/json',
144-
'Authorization': `token ${token}`,
141+
'Content-Type': 'application/json',
142+
'Authorization': `token ${token}`,
145143
},
146144
body: JSON.stringify({
147-
ref: `refs/heads/${NEW_BRANCH}`, // Name of the new branch
148-
sha: sha, // SHA of the base branch (main)
145+
ref: `refs/heads/${NEW_BRANCH}`, // Name of the new branch
146+
sha: sha, // SHA of the base branch (main)
149147
}),
150148
});
151149

152150
const newBranchData = await newBranchResponse.json();
153151

154-
if ( newBranchResponse.ok )
155-
{
152+
if (newBranchResponse.ok) {
156153
console.log('New branch created successfully: ', newBranchData);
157154
return true;
158155
}
159-
else
160-
{
156+
else {
161157
console.error('Error creating new branch: ', newBranchData);
162158
alert("Failed to create branch on project! Error code: " + newBranchResponse.status + ". Please check API Key permissions and try again.")
163159
return false;
164160
}
165161
}
166-
else
167-
{
162+
else {
168163
console.error('Error fetching base branch info:', data);
169164
alert('Error fetching base branch info:', data);
170165
return false;
171166
}
172167
}
173168

174169

175-
async function addFileToBranch(projectURL, token, codeJSONObj)
176-
{
177-
const {owner, repo} = getOrgAndRepoArgsGitHub(projectURL);
170+
async function addFileToBranch(projectURL, token, codeJSONObj) {
171+
const { owner, repo } = getOrgAndRepoArgsGitHub(projectURL);
178172
const FILE_PATH = 'code.json'
179173
const createFileApiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${FILE_PATH}`;
180174
const encodedContent = btoa(codeJSONObj);
181175
console.log("Content: ", encodedContent);
182176
console.log("Branch: ", NEW_BRANCH);
183177

184-
const response = await fetch(createFileApiUrl,
178+
const response = await fetch(createFileApiUrl,
185179
{
186180
method: 'PUT',
187181
headers: {
@@ -203,24 +197,21 @@ async function addFileToBranch(projectURL, token, codeJSONObj)
203197

204198
const data = await response.json()
205199

206-
if ( response.ok )
207-
{
200+
if (response.ok) {
208201
console.log('File added successfully: ', data);
209202
return true;
210203
}
211-
else
212-
{
204+
else {
213205
console.error('Error adding file: ', data);
214206
alert("Failed to add file on project! Error code: " + response.status + ". Please check API Key permissions and try again.")
215207
return false;
216208
}
217209
}
218210

219-
async function createPR(projectURL, token)
220-
{
221-
const {owner, repo} = getOrgAndRepoArgsGitHub(projectURL);
211+
async function createPR(projectURL, token) {
212+
const { owner, repo } = getOrgAndRepoArgsGitHub(projectURL);
222213
const createPrApiUrl = `https://api.github.com/repos/${owner}/${repo}/pulls`;
223-
const response = await fetch(createPrApiUrl,
214+
const response = await fetch(createPrApiUrl,
224215
{
225216
method: 'POST',
226217
headers: {
@@ -240,64 +231,54 @@ async function createPR(projectURL, token)
240231

241232
const data = await response.json();
242233

243-
if (response.ok)
244-
{
234+
if (response.ok) {
245235
console.log('Pull request created successfully: ', data);
246236
return true;
247237
}
248-
else
249-
{
238+
else {
250239
console.error("Error creating PR!: ", data);
251240
alert("Failed to create PR on project! Error code: " + response.status + ". Please check API Key permissions and try again.")
252241
return false;
253242
}
254243
}
255244

256245
// Creates PR on requested project
257-
async function createProjectPR(event){
246+
async function createProjectPR(event) {
258247
event.preventDefault();
259248

260249
var textArea = document.getElementById("json-result");//Step 1
261250
var codeJSONObj = JSON.parse(textArea.value)
262-
263-
if('gh_api_key' in window)
264-
{
251+
252+
if ('gh_api_key' in window) {
265253
var apiKey = window.gh_api_key;
266-
267-
if ('repositoryURL' in codeJSONObj)
268-
{
254+
255+
if ('repositoryURL' in codeJSONObj) {
269256
var prCreated = false;
270257
//Step 1
271-
const branchCreated = await createBranchOnProject(codeJSONObj.repositoryURL,apiKey);
272-
if (branchCreated)
273-
{
258+
const branchCreated = await createBranchOnProject(codeJSONObj.repositoryURL, apiKey);
259+
if (branchCreated) {
274260
const fileAdded = await addFileToBranch(codeJSONObj.repositoryURL, apiKey, textArea.value);
275261

276-
if (fileAdded)
277-
{
262+
if (fileAdded) {
278263
prCreated = await createPR(codeJSONObj.repositoryURL, apiKey);
279-
if(prCreated)
280-
{
264+
if (prCreated) {
281265
console.log("PR successfully created!");
282266
alert("PR has been created!");
283267
}
284268
}
285269
}
286-
else
287-
{
270+
else {
288271
console.error("Could not create branch on requested repository with the requested API key!");
289272
alert("Could not create branch on requested repository with the requested API key!");
290273
}
291274
}
292-
else
293-
{
275+
else {
294276
console.error("No URL found!");
295277
alert("No URL given for project! Please provide project URL in repositoryURL text box");
296278
}
297-
279+
298280
}
299-
else
300-
{
281+
else {
301282
console.error("No API key found!");
302283
alert("No API Key in submitted data! Please provide an API key");
303284
}
@@ -328,27 +309,27 @@ async function emailFile(event) {
328309

329310
const codeJson = document.getElementById("json-result").value
330311
const jsonObject = JSON.parse(codeJson);
331-
332-
try {
333-
const cleanData = {...jsonObject};
334-
delete cleanData.submit;
335312

336-
const jsonString = JSON.stringify(cleanData, null, 2);
313+
try {
314+
const cleanData = { ...jsonObject };
315+
delete cleanData.submit;
316+
317+
const jsonString = JSON.stringify(cleanData, null, 2);
337318

338-
const subject = "Code.json generator Results";
339-
const body = `Hello,\n\nHere are the code.json results:\n\n${jsonString}\n\nThank you!`;
319+
const subject = "Code.json generator Results";
320+
const body = `Hello,\n\nHere are the code.json results:\n\n${jsonString}\n\nThank you!`;
340321

341-
const recipients = ["opensource@cms.hhs.gov"];
322+
const recipients = ["opensource@cms.hhs.gov"];
342323

343-
const mailtoLink = `mailto:${recipients}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
324+
const mailtoLink = `mailto:${recipients}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
344325

345-
window.location.href = mailtoLink;
326+
window.location.href = mailtoLink;
346327

347-
console.log("Email client opened");
348-
} catch {
349-
console.error("Error preparing email:", error);
350-
showNotificationModal("Error preparing email. Please try again or copy the data manually.", 'error');
351-
}
328+
console.log("Email client opened");
329+
} catch {
330+
console.error("Error preparing email:", error);
331+
showNotificationModal("Error preparing email. Please try again or copy the data manually.", 'error');
332+
}
352333
}
353334

354335
window.createCodeJson = createCodeJson;

0 commit comments

Comments
 (0)