Author SHA1 Message Date
brausjonas e526b6c804 Bug Fixed 2023-06-16 09:01:11 +02:00
brausjonas 3e381687c2 Only Errors Shown In Side Bar (No Okay Days) 2023-06-16 08:59:40 +02:00
brausjonas 38ce89c295 Clicking On ALl Tiles Bug Fixed 2023-06-16 08:55:27 +02:00
brausjonas 79c1c93bd2 Database with Module ID for entries 2023-06-15 22:07:21 +02:00
brausjonas 5eba3a6733 Multiselected For Lectures / Modules Implemented
Der Multiselect funktioniert auf seitens des Frontends und des Backends. Allerdings haben Termine noch nicht die Spalte moduleID, weswegen entries für zwei modules eines Dozenten innerhalb eines Semesters gleich angezeigt werden.
2023-06-15 22:04:57 +02:00
AliGitGut cff384f5b4 Bugfix Inputform
Bugfix for the start and enddate
2023-06-14 12:24:20 +02:00
AliGitGut eb69b97b9d Datum Validierung
Start eines Theorie Semester kann nicht hinter dem Ende des Theorie Semesters liegen
2023-06-14 11:29:31 +02:00
AlexE030 c02a0592ed Added Submitbutton 2023-06-13 19:28:32 +02:00
brausjonas e65ae7b90e Merge branch 'main' of https://github.com/DHBWLoerrach/TIF22A_AnwProjekt_B 2023-06-13 15:08:59 +02:00
brausjonas ac97e1937f Fixed Feiertage 2023-06-13 15:08:50 +02:00
AliGitGut 65325046c7 Bugfixing
Inputform bugfix
2023-06-13 15:03:06 +02:00
brausjonas fd6af0cdf4 Gray out logic restored 2023-06-13 14:58:29 +02:00
AliGitGut acf4b7d89a Feiertage Implementiert
Feiertage werden nun ausgegraut ^^
2023-06-13 14:28:19 +02:00
brausjonas 5c0de04f29 Database Corrected (not corrupt anymore, No server problem)) 2023-06-13 14:11:13 +02:00
brausjonas 7009a48735 New Database from Website 2023-06-13 13:44:26 +02:00
brausjonas 04df42b67a Push From Amira 2023-06-13 13:37:23 +02:00
brausjonas b89a1fd2fe Revert "Font size change"
This reverts commit a57e2b589a.
2023-06-13 13:35:16 +02:00
Amira24523 a57e2b589a Font size change 2023-06-13 13:29:40 +02:00
AliGitGut 0392c45eea Vorbereitung Progessbar
Semester Tiles angepasst für Progessbar implementierung
2023-06-10 01:18:46 +02:00
AliGitGut e9de6c41af Backend Statusbar Update
Backend Statusbar Funktionen hinzugefügt
2023-06-10 00:56:54 +02:00
AliGitGut 43165d7756 Overlap Bugfix
If any entries overlaps with the Users entries from other Semesters, the users entries will be cut of
2023-06-10 00:01:53 +02:00
brausjonas 092f7d3a8a Added Help Page 2023-06-09 22:49:56 +02:00
AliGitGut 394b920a4e All Entrys Shown for Lecturer
A lecturer can now see all his entries in his lecture view. Entries from other semester are blue colored, cant be configured from the from lecture view and are not of relevance for the rule semester, since they don´t apply for the students, only for the lecturer him- or herself
2023-06-09 21:35:02 +02:00
brausjonas b4020d0756 Final Bug Fix For Validation 2023-06-09 17:10:29 +02:00
brausjonas b1da16aed5 Bug In Validation Fixed 2023-06-09 16:44:53 +02:00
brausjonas 7b2602172e Valditions Displayed 2023-06-09 16:29:36 +02:00
brausjonas 74fbf38ecd Days Grayed Out 2023-06-09 14:22:18 +02:00
brausjonas b93c05b874 Calender Side Bar Autoscroll behaviour 2023-06-09 00:30:51 +02:00
brausjonas 9368ea423d Bug Finally Fixed 2023-06-09 00:10:22 +02:00
brausjonas 2280ff64a4 Bug Fixed 2023-06-09 00:07:02 +02:00
AliGitGut 2be842abea Highlight Added
Bugs
2023-06-08 23:58:12 +02:00
brausjonas dc5815d73d Calender Sidebar Get Months from Semester 2023-06-08 23:06:37 +02:00
brausjonas 8eed2746e9 Calender Side Bar on Click 2023-06-08 22:50:33 +02:00
AliGitGut 2abef513fe Calendar Sidebar Fixed
@AlexE030 and me
the days start at the right weekday now
2.30 am coding sessions are the best
2023-06-08 02:36:36 +02:00
brausjonas 964934690b Calender Validation Not Shown Explicit Error message
Die Fehlermeldung wird bereits in einem Feld gespeichert, jedoch noch nicht abgespeichert
PUUUUSH
2023-06-08 02:29:00 +02:00
AliGitGut 76ff99a365 Calendar Sidebar Added
Calendar Sidebar edited and added to the CalendarView
2023-06-08 00:27:20 +02:00
AliGitGut 62902d1b47 Performance Update
Dozenten Freigabe/Blockade möglich
Zurück Button Implementiert
PUUUUSH (insider für Jonas)
2023-06-07 23:06:08 +02:00
brausjonas 3b788cdd6b Semester Tile Takes Color Property 2023-06-07 22:28:54 +02:00
brausjonas 530047ac68 Connected SemesterOverviewLecturer and Calenderview 2023-06-07 21:58:54 +02:00
brausjonas 7446fca94d Lower Case Bug Fixed on Backend 2023-06-07 21:27:34 +02:00
AlexE030 88947e36f0 Username Bugfix 2023-05-30 15:50:54 +02:00
brausjonas b298fe0bdf Create README.md 2023-05-30 15:11:20 +02:00
brausjonas e33301f02e Prevent AutoScroll On Resize 2023-05-30 04:00:17 +02:00
brausjonas dac59d4a23 Use URL as Constant 2023-05-30 02:28:51 +02:00
AliGitGut a0d6d15099 Lecturer Dashboard Finished Version 2023-05-29 23:32:29 +02:00
AliGitGut dc708392c8 Dashboard Test 1
Lecturer Dashboard
2023-05-29 21:50:45 +02:00
brausjonas d90303f5c5 Revert "Init"
This reverts commit aa790a20d6.
2023-05-29 21:30:15 +02:00
brausjonas aa790a20d6 Init 2023-05-29 21:28:48 +02:00
brausjonas 866dfe9e2b Zoom Again Added to Calender View with + and - key 2023-05-26 16:27:20 +02:00
brausjonas d5443c87d0 Auto Scroll CalenderView to Middle 2023-05-26 15:43:41 +02:00
brausjonas aada7872da Datum neben dem Wochentg 2023-05-26 15:30:43 +02:00
AliGitGut 594c82ce23 Starttime edited
Starttime can be changed now
2023-05-26 14:50:04 +02:00
brausjonas edaba10719 New Calender View Design 2023-05-26 14:24:38 +02:00
brausjonas cf7201bc80 Backend Aufgeräumt 2023-05-26 13:36:28 +02:00
Amira24523 a8aa28e245 Calender Sync
Kalenderansicht synchronisieren sich automatisch
2023-05-26 12:00:04 +02:00
brausjonas 76243295cc Add files via upload 2023-05-26 10:28:09 +02:00
brausjonas b4c71af857 Calender View Sync Prototype Working Correctly 2023-05-26 02:10:15 +02:00
brausjonas f52d4275ba New Calender View Logic Concept 2023-05-26 00:46:50 +02:00
brausjonas 0c42a5820a Merge branch 'JonasTestBranch' into main 2023-05-25 23:01:50 +02:00
brausjonas 09d46a9faf Edit Logic Finished 2023-05-25 13:36:38 +02:00
brausjonas ac9fa44b99 Edit Function Finished (Semester and Modules)
Man kann bis jetzt eine dozenten noch nicht "abwählen"
2023-05-25 13:22:22 +02:00
brausjonas 00d57da32d Test Input Form reload data 2023-05-25 02:06:30 +02:00
brausjonas 15d325815d Bug Fix 2023-05-24 17:36:38 +02:00
brausjonas 7703b0676d Modules On Push 2023-05-24 17:30:16 +02:00
brausjonas f42f2df078 FrontEnd Bug Fix 2023-05-24 16:05:21 +02:00
brausjonas 337aea6a65 Merge branch 'DesignIdea' into main 2023-05-24 12:47:35 +02:00
brausjonas 9255fb8e9b Updated Maven File for Build 2023-05-24 09:31:43 +02:00
75 changed files with 205725 additions and 1589371 deletions

No files matched your search

Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
# TIF22A_AnwProjekt_B
Team B im Anwendungsprojekt (TIF22A)
Website can be accessed under: http://lectureplanner.de/ (caution no https, only http)
-84
View File
@@ -9,7 +9,6 @@
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"autoprefixer": "10.4.14", "autoprefixer": "10.4.14",
"daisyui": "^2.51.6",
"next": "13.3.4", "next": "13.3.4",
"postcss": "8.4.23", "postcss": "8.4.23",
"react": "18.2.0", "react": "18.2.0",
@@ -450,43 +449,6 @@
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==" "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="
}, },
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
"integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
"dependencies": {
"color-convert": "^2.0.1",
"color-string": "^1.9.0"
},
"engines": {
"node": ">=12.5.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/commander": { "node_modules/commander": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -500,15 +462,6 @@
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
}, },
"node_modules/css-selector-tokenizer": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/css-selector-tokenizer/-/css-selector-tokenizer-0.8.0.tgz",
"integrity": "sha512-Jd6Ig3/pe62/qe5SBPTN8h8LeUg/pT4lLgtavPf7updwwHpvFzxvOQBHYj2LZDMjUnBzgvIUSjRcf6oT5HzHFg==",
"dependencies": {
"cssesc": "^3.0.0",
"fastparse": "^1.1.2"
}
},
"node_modules/cssesc": { "node_modules/cssesc": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
@@ -520,25 +473,6 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/daisyui": {
"version": "2.51.6",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-2.51.6.tgz",
"integrity": "sha512-JRqOKayuFCmWe4X4k6Qvx1y7V/VNao8U5eTSOhusOKIzCsYqf56+TCSe4d7zmqGE0V6JiLDYAT8JeoWUeRKFCw==",
"dependencies": {
"color": "^4.2",
"css-selector-tokenizer": "^0.8.0",
"postcss-js": "^4.0.0",
"tailwindcss": "^3"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/daisyui"
},
"peerDependencies": {
"autoprefixer": "^10.0.2",
"postcss": "^8.1.6"
}
},
"node_modules/didyoumean": { "node_modules/didyoumean": {
"version": "1.2.2", "version": "1.2.2",
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -588,11 +522,6 @@
"node": ">= 6" "node": ">= 6"
} }
}, },
"node_modules/fastparse": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/fastparse/-/fastparse-1.1.2.tgz",
"integrity": "sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ=="
},
"node_modules/fastq": { "node_modules/fastq": {
"version": "1.15.0", "version": "1.15.0",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz",
@@ -702,11 +631,6 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
}, },
"node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ=="
},
"node_modules/is-binary-path": { "node_modules/is-binary-path": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
@@ -1256,14 +1180,6 @@
"loose-envify": "^1.1.0" "loose-envify": "^1.1.0"
} }
}, },
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz",
+21
View File
@@ -0,0 +1,21 @@
import Button from "@/components/Button";
import {useRouter} from "next/router";
import {baseURL} from "@/components/Constants";
import {arrowLeft} from "@/components/Icons";
export default function Back(p)
{
return(
<div style={{
position : "absolute",
left : 20,
top : 20,
width : 60,
height : 60
}}>
<Button onClick={() => p.onClick()} icon={arrowLeft} color={"#77932b"} width={75} height={40}/>
</div>
)
}
+88 -21
View File
@@ -1,34 +1,88 @@
import {useEffect, useRef} from "react";
let startParts = [] let startParts = []
let endParts = [] let endParts = []
const months = [["Januar", 31], ["Februar", 28], ["März", 31], ["April", 30], ["Mai", 31], ["Juni", 30], ["Juli", 31], ["August", 31], ["September", 30], ["Oktober", 31], ["November", 30], ["Dezember", 31]] const months = [["Januar", 31], ["Februar", 28], ["März", 31], ["April", 30], ["Mai", 31], ["Juni", 30], ["Juli", 31], ["August", 31], ["September", 30], ["Oktober", 31], ["November", 30], ["Dezember", 31]]
const days = months.map((month => month[1])) const days = months.map((month => month[1]))
let result = [] let result = []
let check = true let startDate
let calculatedDay = []
const weekdays = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] const weekdays = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
let lastMonth = 0
export default function BasicDateCalendar(p) { export default function BasicDateCalendar(p) {
if (check) {
generateCalendar("01.12.2024", "15.09.2025") const ref = useRef(null)
check = false
function getBackMonthColor(monthIndex)
{
let date = new Date(parseInt(startParts[2]), parseInt(startParts[1]) + monthIndex - 1, 1)
if (date.getFullYear() === p.highlightYear && date.getMonth() === p.highlightMonth)
{
if(lastMonth !== p.highlightMonth)
{
ref.current.scrollTo({top: 290 * monthIndex - 270, behavior: "smooth"})
} }
lastMonth = p.highlightMonth
return true
}else
return false
}
useEffect(() => {
startParts = []
endParts = []
result = []
calculatedDay = []
startDate = new Date(p.startyear, 0 ,p.startday)
let endDate = new Date(p.endyear, 0 , p.endday)
let startString = startDate.getDate() + "." + (startDate.getMonth() + 1) + "." + p.startyear
let endString = endDate.getDate() + "." + (endDate.getMonth() + 1) + "." + p.endyear
generateCalendar(startString, endString)
})
return ( return (
<div className={"Allround"} ref={ref}>
<div className={"Down"}> <div className={"Down"}>
{result.map((monthResult, index = 0) => ( {result.map((monthResult, index) => (
<div key={months} className={"A"}> <div className={"A box-shadow"} onClick={() => p.onMonthClick(
<p>{getMonthName(index)}</p> (parseInt(startParts[1]) + index),
<div className={"Days"}> startParts
)} >
<p style={{
textAlign : "center",
marginBottom : 10,
fontSize: 19,
pointerEvents: "none",
backgroundColor: getBackMonthColor(index) ? "#346991":"rgba(0,0,0,0)",
color : getBackMonthColor(index) ? "white":"black",
borderRadius : 10
}}>{getMonthName(index) + " " + new Date(parseInt(startParts[2]), parseInt(startParts[1]) + index - 1, 1).getFullYear()}</p>
<div className={"Days"} style={{
pointerEvents: "none"
}}>
{weekdays.map((weekday) => ( {weekdays.map((weekday) => (
<p key={weekday}>{weekday}</p> <p key={weekday} style={{
pointerEvents: "none"
}}>{weekday}</p>
))} ))}
{freeSpaces(index)}
{monthResult.map((date) => ( {monthResult.map((date) => (
<p key={date}>{date}</p> <p key={date} style={{
pointerEvents: "none"
}}>{date}</p>
))} ))}
</div> </div>
</div> </div>
))} ))}
</div> </div>
</div>
) )
} }
function getMonthName(monthIndex) { function getMonthName(monthIndex) {
if (startParts[1] - 1 + monthIndex < 12) { if (startParts[1] - 1 + monthIndex < 12) {
return months[startParts[1] - 1 + monthIndex][0]; return months[startParts[1] - 1 + monthIndex][0];
@@ -37,7 +91,6 @@ function getMonthName(monthIndex) {
} }
} }
function generateCalendar(start, ende) function generateCalendar(start, ende)
{ {
splitter(start, ende) splitter(start, ende)
@@ -54,6 +107,7 @@ function generateCalendar(start, ende)
) )
{ {
monthResult.push(j); monthResult.push(j);
calculateDay(startParts[2], i, j)
} }
} }
result.push(monthResult); result.push(monthResult);
@@ -67,6 +121,7 @@ function generateCalendar(start, ende)
if (new Date(endParts[2], h, g) <= new Date(endParts[2], endParts[1] - 1, endParts[0])) if (new Date(endParts[2], h, g) <= new Date(endParts[2], endParts[1] - 1, endParts[0]))
{ {
monthResultNewYear.push(g); monthResultNewYear.push(g);
calculateDay(endParts[2], h, g)
} }
} }
result.push(monthResultNewYear); result.push(monthResultNewYear);
@@ -85,7 +140,8 @@ function generateCalendar(start, ende)
new Date(startParts[2], i, j) <= new Date(startParts[2], endParts[1] - 1, endParts[0]) new Date(startParts[2], i, j) <= new Date(startParts[2], endParts[1] - 1, endParts[0])
) )
{ {
monthResult.push(j); monthResult.push(j)
calculateDay(startParts[2], i, j)
} }
} }
result.push(monthResult); result.push(monthResult);
@@ -93,10 +149,29 @@ function generateCalendar(start, ende)
} }
} }
function calculateDay(x, i, j){
if (j == startDate.getDate() && i == startDate.getMonth() || j == 1){
let monthStart = new Date(x, i, j)
if (monthStart.getDay() == 0)
calculatedDay.push(6)
else calculatedDay.push(monthStart.getDay() - 1)
}
}
function freeSpaces(index)
{
let arrayTest = []
for (let i = 0; i < calculatedDay[index]; i++) {
arrayTest.push(<p style={{
pointerEvents: "none"
}}></p>)
}
return arrayTest
}
function splitter(startDate, endDate) function splitter(startDate, endDate)
{ {
startParts = startDate.split(".") startParts = startDate.split(".")
//Transformer()
if (startParts[1][0] === 0) //prüft ob die erste Stelle des Monats eine 0 vorne stehen hat if (startParts[1][0] === 0) //prüft ob die erste Stelle des Monats eine 0 vorne stehen hat
{ {
startParts[1] = startParts[1][1] //überschreibt den Monat ohne die 0 startParts[1] = startParts[1][1] //überschreibt den Monat ohne die 0
@@ -107,11 +182,3 @@ function splitter(startDate, endDate)
endParts[1] = endParts[1][1] //überschreibt den Monat ohne die 0 endParts[1] = endParts[1][1] //überschreibt den Monat ohne die 0
} }
} }
function Transformer()
{
let formattedDateStr = startParts[1] + "/" + startParts[0] + "/" + startParts[2];
console.log(formattedDateStr)
let weekday = new Date(formattedDateStr).getDay();
console.log(weekday);
}
@@ -1,9 +0,0 @@
export class CalenderEntry
{
constructor(start_point, end_point)
{
this.start_point = start_point;
this.end_point = end_point;
this.colorID = 0;
}
}
File diff suppressed because it is too large. Load diff
+2
View File
@@ -0,0 +1,2 @@
//export const baseURL = "http://185.245.96.48:8080"
export const baseURL = "http://localhost:8080"
+6 -10
View File
@@ -4,20 +4,16 @@ function addDays(date, days) {
return result; return result;
} }
export default function DateElement(props){ export default function DateElement(p){
let startDate;
let endDate;
const currDate = new Date();
startDate = addDays(currDate, (currDate.getDay()-1)*-1); //berechnet den Montag der aktuellen Woche let startDate = new Date(p.year, 0, p.startday);
startDate = addDays(startDate, props.week*7); //erhöht das Datum um 7 Tage für jede Woche, die weiter geklickt wurde. let endDate = new Date(p.year, 0, p.startday + 5);
endDate = addDays(startDate, 6);
const startDateString = `${startDate.getDate()}.${startDate.getMonth()+1}.${startDate.getFullYear()}`; let startDateString = `${startDate.getDate()}.${startDate.getMonth()+1}.${startDate.getFullYear()}`;
const endDateString = `${endDate.getDate()}.${endDate.getMonth()+1}.${endDate.getFullYear()}`; let endDateString = `${endDate.getDate()}.${endDate.getMonth()+1}.${endDate.getFullYear()}`;
return ( return (
<> <>
<div className="dateElement round-border"> <div className="dateElement round-border box-shadow">
<p>{startDateString} - {endDateString}</p> <p>{startDateString} - {endDateString}</p>
</div> </div>
</> </>
+8
View File
@@ -0,0 +1,8 @@
export const ErrorType = {
Okay: "Okay",
TooLong: "Zu lang, maximal 8h pro Tag!",
TooEarly: "Wenn möglich nicht vor 8:00",
TooLate: "Wenn möglich nicht nach 17:00",
NotEnoughLunchTime: "Mind. 45min Pause zwischen 11:00 - 14:00",
Saturday: "Wenn möglich nicht am Samstag"
}
+19
View File
@@ -0,0 +1,19 @@
import Button from "@/components/Button";
import {helpButton} from "@/components/Icons";
import {useRouter} from "next/router";
export default function HelpButton(p)
{
const router = useRouter()
return (
<div style={{
position: "absolute",
bottom: 20,
right: 20,
borderRadius: 15
}} className={"box-shadow"}>
<Button width={40} height={40} color={"white"} icon={helpButton} onClick={() => router.push("/help")}/>
</div>
)
}
+4
View File
@@ -13,3 +13,7 @@ export const deleteItem = `<svg xmlns="http://www.w3.org/2000/svg" fill="black"
export const editItem = `<svg xmlns="http://www.w3.org/2000/svg" fill="black" class="bi bi-pencil-fill" viewBox="0 0 16 16"> export const editItem = `<svg xmlns="http://www.w3.org/2000/svg" fill="black" class="bi bi-pencil-fill" viewBox="0 0 16 16">
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/> <path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/>
</svg>` </svg>`
export const helpButton = `<svg xmlns="http://www.w3.org/2000/svg" fill="black" class="bi bi-question" viewBox="0 0 16 16">
<path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"/>
</svg>`
+305 -191
View File
@@ -2,244 +2,358 @@ import Button from "@/components/Button";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import {useEffect, useState} from "react"; import {useEffect, useState} from "react";
import Background from "@/components/Background"; import Background from "@/components/Background";
import {baseURL} from "@/components/Constants";
import Back from "@/components/Back";
let userInfo = [] let modulesDummy = [
["Analysis", "Theo Inf 1"],
["Lineare Algebra", "Anwendungsprojekt"],
["Theo Inf 3", "Software Eng"],
["Security", "BWL"],
["Software Eng", "Security"],
["Studienarbeit", "Bachelor"]
]
let tempSemesterNumber = 0
let update = false
let baseMapping = []
export default function InputForm(p) { export default function InputForm(p) {
class UserInfo { const [startDate, setStartDate] = useState("0000-00-00")
constructor(userid, modules) { const [endDate, setEndDate] = useState("0000-00-00")
this.userid = userid; const [courseName, setCourseName] = useState("")
this.module = modules; const [semesterNumber, setSemesterNumber] = useState(0)
this.checked = false; const [users, setUsers] = useState([])
} const [modulesSelectorValues, setModulesSelectorValues] = useState(["nothing", "nothing"])
const [userModulesMapping, setUserModulesMapping] = useState({})
setChecked(checked) { const [isChecked, setIsChecked] = useState([])
this.checked = checked; const [isActivated, setIsActivated] = useState([])
} const router = useRouter()
setModule(module) {
this.module = module;
}
}
let startDateParam = "";
let endDateParam = "";
let courseNameParam = "";
if (p.startDate != null) startDateParam = p.startDate;
if (p.endDate != null) endDateParam = p.endDate;
if (p.courseName != null) courseNameParam = p.courseName;
const router = useRouter();
const [startDate, setStartDate] = useState(startDateParam);
const [endDate, setEndDate] = useState(endDateParam);
const [courseName, setCourseName] = useState(courseNameParam);
const [users, setUsers] = useState([]);
async function getAllUsers() {
let sessionid = localStorage.getItem("sessionid");
let url = "http://localhost:8080/users/all?sessionid=" + sessionid;
await fetch(url).then(response => response.json()).then(user => setUsers(user));
}
useEffect(() => { useEffect(() => {
userInfo = []; let base = baseURL + "/semester/id?sessionid=" + localStorage.getItem("sessionid") + "&id=" + localStorage.getItem("currentsid")
getAllUsers(); fetch(base).then(r => r.json()).then(j => {
setCourseName(j.name)
let tempStartDate = new Date(parseInt(j.startyear), 0, parseInt(j.startday))
let tempEndDate = new Date(parseInt(j.endyear), 0, parseInt(j.endday))
setStartDate(tempStartDate.getFullYear() + "-" + ((tempStartDate.getMonth() + 1).toString().padStart(2, "0")) + "-" + tempStartDate.getDate().toString().padStart(2, "0"))
setEndDate(tempEndDate.getFullYear() + "-" + ((tempEndDate.getMonth() + 1).toString().padStart(2, "0")) + "-" + tempEndDate.getDate().toString().padStart(2, "0"))
setSemesterNumber(j.number)
tempSemesterNumber = j.number
}).then(() => {
readModules()
update = true
}).catch(() => readModules())
}, []) }, [])
async function onCreateClicked() { function readModules() {
let startSplit = startDate.split("-"); let usersTemp = []
let endSplit = endDate.split("-");
let startYear = parseInt(startSplit[0]);
let endYear = parseInt(endSplit[0]);
//month - 1 because jan = 0, day like month... but because of next lines 3 to 4 not - 1 let userURL = baseURL + "/users/all?sessionid=" + localStorage.getItem("sessionid")
let startInternalDate = new Date(startYear, parseInt(startSplit[1]) - 1, parseInt(startSplit[2])) fetch(userURL).then(r => r.json()).then(j => {
let endInternalDate = new Date(endYear, parseInt(endSplit[1]) - 1, parseInt(endSplit[2])) setUsers(j)
usersTemp = j
let temp = [false, false, false]
let temp2 = []
for (let i = 0; i < j.length; i++) {
temp.push(false)
temp2.push(false)
}
setIsChecked(temp)
setIsActivated(temp2)
}).then(() => {
let modulesURL = baseURL + "/module/bysemesterid?sessionid=" + localStorage.getItem("sessionid") + "&semesterid=" + localStorage.getItem("currentsid");
fetch(modulesURL).then(r => r.json()).then(j => {
let startDayInYear = Math.round((startInternalDate - new Date(startYear, 0, 0)) / (1000 * 60 * 60 * 24)); setUserModulesMapping(j)
let endDayInYear = Math.round((endInternalDate - new Date(endYear, 0, 0)) / (1000 * 60 * 60 * 24)); baseMapping = j
let id = p.courseName == null ? 0 : localStorage.getItem("currentsid"); let temp = isChecked.slice()
let temp2 = isActivated.slice()
let json = { for (let i = 0; i < usersTemp.length; i++) {
"id": id, let currentUser = usersTemp[i]
let found = false
let foundModuleLast = null
for (let f = 0; f < j.length; f++) {
let currentModule = j[f]
if (currentModule.userid === currentUser.id) {
found = true
foundModuleLast = currentModule
}
}
if (found) {
temp[i] = true
temp2[i] = foundModuleLast.activated === 1
}
}
setIsChecked(temp)
setIsActivated(temp2)
})
}).then(() => {
setModulesSelectorValues(modulesDummy[tempSemesterNumber])
})
}
function onCourseNameChange(e) {
setCourseName(e.target.value)
}
function onStartDateChange(e) {
setStartDate(e.target.value)
}
function onEndDateChange(e) {
setEndDate(e.target.value)
}
function onSemesterNumberChange(e) {
setSemesterNumber(e.target.value)
setModulesSelectorValues(modulesDummy[e.target.value])
}
function isOptionSelected(e, userid) {
let found = false;
for (let i = 0; i < userModulesMapping.length; i++) {
let current = userModulesMapping[i]
if (current.name === e && current.userid === userid) {
found = true;
}
}
return found;
}
function onCheckedChange(e, index) {
let temp = isChecked.slice()
temp[index] = e.target.checked
setIsChecked(temp)
if (!e.target.checked) {
let temp = []
let currentUser = users[index]
for (let j = 0; j < userModulesMapping.length; j++) {
if (userModulesMapping[j].userid !== currentUser.id) {
temp.push(userModulesMapping[j])
}
}
setUserModulesMapping(temp)
}
}
function onActivatedChange(e, index) {
let temp = isActivated.slice()
temp[index] = e.target.checked
setIsActivated(temp)
let userid = users[index].id
for (let j = 0; j < userModulesMapping.length; j++) {
if (userModulesMapping[j].userid === userid) {
userModulesMapping[j].activated = e.target.checked ? 1 : 0
}
}
}
function onModuleSelectionChange(e, index) {
let userid = users[index].id
let newMapping = []
let oldNamesIds = new Map()
for (let j = 0; j < userModulesMapping.length; j++) {
let currentModuleMapping = userModulesMapping[j]
if (currentModuleMapping.userid != userid) {
newMapping.push(currentModuleMapping)
} else {
oldNamesIds.set(currentModuleMapping.name, currentModuleMapping.id)
}
}
let found = false
for (let i = 0; i < e.target.options.length; i++) {
let currentOption = e.target.options[i]
if (currentOption.selected) {
found = true
newMapping.push({
"id": oldNamesIds.has(currentOption.value) ? oldNamesIds.get(currentOption.value) : -1,
"userid": userid,
"semesterid": -1,
"name": currentOption.value,
"activated": isActivated[index] ? 1 : 0
})
}
}
let temp = isChecked.slice()
temp[index] = found
setIsChecked(temp)
setUserModulesMapping(newMapping)
}
function onButtonAbort() {
router.back()
}
function onButtonSave() {
let tempDateStart = new Date(parseInt(startDate.split("-")[0]), parseInt(startDate.split("-")[1]) - 1, parseInt(startDate.split("-")[2]))
let tempDateEnd = new Date(parseInt(endDate.split("-")[0]), parseInt(endDate.split("-")[1]) - 1, parseInt(endDate.split("-")[2]))
let startDayInYear = Math.round((tempDateStart - new Date(tempDateStart.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
let endDayInYear = Math.round((tempDateEnd - new Date(tempDateEnd.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
let semesterJson = {
"id": update ? localStorage.getItem("currentsid") : 0,
"startday": startDayInYear, "startday": startDayInYear,
"endday": endDayInYear, "endday": endDayInYear,
"name": courseName, "name": courseName,
"startyear": startYear, "startyear": tempDateStart.getFullYear(),
"endyear": endYear "endyear": tempDateEnd.getFullYear(),
"number": semesterNumber
} }
let url = "http://localhost:8080/semester?sessionid=" + localStorage.getItem("sessionid"); fetch(baseURL + "/semester?sessionid=" + localStorage.getItem("sessionid"), {
let method = p.courseName == null ? "POST" : "PUT"; method: update ? "PUT" : "POST",
await fetch(url, {
method: method,
headers: {"Content-Type": "application/json"}, headers: {"Content-Type": "application/json"},
body: JSON.stringify(json) body: JSON.stringify(semesterJson)
}).then(response => response.json()).then(semester => console.log(semester)); }).then(r => r.json()).then(async sem => {
let semesterID = sem.id
for (let i = 0; i < baseMapping.length; i++) {
router.back(); let found = false
} for (let j = 0; j < userModulesMapping.length; j++) {
if (baseMapping[i].name === userModulesMapping[j].name) {
function onModuleClicked(user, module) { found = true
let found = false;
for (let i = 0; i < userInfo.length; i++) {
let current = userInfo[i];
if (current !== undefined && current.userid === user.id) {
userInfo[i].setModule(module);
found = true;
} }
} }
if (!found) { if (!found) {
userInfo.push(new UserInfo(user.id, module)); fetch(baseURL + "/module?sessionid=" + localStorage.getItem("sessionid") + "&id=" + baseMapping[i].id, {
method: "DELETE"
})
} }
} }
function onCheckBoxClicked(user, e) { for (let i = 0; i < userModulesMapping.length; i++) {
onModuleClicked(user, "");
let found = false; userModulesMapping[i].semesterid = semesterID
setTimeout(() => {
console.log(userModulesMapping[i])
fetch(baseURL + "/module?sessionid=" + localStorage.getItem("sessionid"), {
method: userModulesMapping[i].id === -1 ? "POST" : "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(userModulesMapping[i])
})
}, i * 100)
for (let i = 0; i < userInfo.length; i++) {
let current = userInfo[i];
if (current !== undefined && current.userid === user.id) {
userInfo[i].setChecked(e.target.checked);
found = true;
}
} }
})
if (!found) { router.back()
let temp = new UserInfo(user.id, "");
temp.setChecked(e.target.checked);
userInfo.push(temp);
}
} }
return ( return (
<> <>
<Background/> <Background/>
<div className="inputForm box-shadow"> <div className={"box-shadow input-form round-border"}>
<p style={{
fontSize: "18px", <p>Kursname</p>
color: "#777777", <input type={"text"} className={"box-shadow round-border"} style={{padding: 8, width: "100%"}}
fontWeight: 500, onChange={e => onCourseNameChange(e)} value={courseName}/>
width: 150
}}>SemesterName</p> <div style={{display: "flex", justifyContent: "flex-start", gap: 40}}>
<input className="courseNameInput box-shadow" value={courseName} <p>Theorie Anfang</p>
onChange={(e) => setCourseName(e.target.value)}/> <p>Theorie Ende</p>
<div className="semesterRangeInput">
<div className="semesterDateLables">
<p className="semesterDateLable" style={{
fontSize: " 18px",
color: "#777777",
fontWeight: 500,
width: 150
}}>Semesterstart</p>
<p className="semesterDateLable" style={{
fontSize: " 18px",
color: "#777777",
fontWeight: 500,
width: 150
}}>Semesterende</p>
</div> </div>
<div className="semesterDateInputPair"> <div style={{display: "flex", justifyContent: "flex-start", gap: 20}}>
<input type="date" id="start" className={"box-shadow selector"} value={startDate} <input type={"date"} className={"box-shadow round-border"} style={{padding: 8}}
style={{padding: 5}} onChange={e => onStartDateChange(e)} value={startDate}/>
onChange={(e) => setStartDate(e.target.value)}/> <input type={"date"} className={"box-shadow round-border"} style={{padding: 8}}
<p className="inputFieldSeperator">-</p> onChange={e => onEndDateChange(e)} value={endDate}/>
<input type="date" id="start" className={"box-shadow selector"} value={endDate}
style={{padding: 5}}
onChange={(e) => setEndDate(e.target.value)}/>
</div> </div>
</div>
<div className="round-border dozentSelector"> <p>Semester Wählen</p>
<select className={"round-border box-shadow"} style={{padding: 5, width: "100%"}} value={semesterNumber}
onChange={e => onSemesterNumberChange(e)}>
<option value={0}>1. Semester</option>
<option value={1}>2. Semester</option>
<option value={2}>3. Semester</option>
<option value={3}>4. Semester</option>
<option value={4}>5. Semester</option>
<option value={5}>6. Semester</option>
</select>
<div className={"table-wrapper"}>
<table> <table>
<tbody> <tbody>
<tr> <tr>
<th style={{ <th>Wählen</th>
fontSize: " 18px", <th>Freischalten</th>
color: "#777777", <th>Dozent</th>
fontWeight: 500, <th>Modul</th>
}}>Wählen
</th>
<th style={{
fontSize: " 18px",
color: "#777777",
fontWeight: 500,
}}>Freischalten
</th>
<th style={{
fontSize: " 18px",
color: "#777777",
fontWeight: 500,
textAlign: "center"
}}>Dozent
</th>
<th style={{
fontSize: " 18px",
color: "#777777",
fontWeight: 500,
textAlign: "center",
}}>Modul
</th>
</tr> </tr>
{users.map(user => ( {
users.map((user, index) => (
<tr> <tr>
<td>
<td><div style={{ <input type={"checkbox"} checked={isChecked[index]}
display: "flex", onChange={e => onCheckedChange(e, index)}/>
flexDirection: "row", </td>
justifyContent: "center", <td>
}}><input type="checkbox" onChange={(e) => { <input type={"checkbox"} checked={isActivated[index]}
onCheckBoxClicked(user, e); onChange={e => onActivatedChange(e, index)}/>
}}/></div></td> </td>
<td>
<td><div style={{ {user.firstName + " " + user.lastName}
display: "flex", </td>
flexDirection: "row", <td>
justifyContent: "center", <select multiple={true} className={"box-shadow round-border"}
}}><input type="checkbox" onChange={(e) => { style={{padding: 5}}
onCheckBoxClicked(user, e); onChange={e => onModuleSelectionChange(e, index)}>
}}/></div></td> {modulesSelectorValues.map(msv => (
<td style={{}}>{user.firstName + " " + user.lastName}</td> <option value={msv}
<select id={"userSelect"} name={"userSelect"} className={"box-shadow selector"} selected={isOptionSelected(msv, user.id)}>{msv}</option>
multiple={false} style={{
maxHeight: 80,
marginTop: 10,
padding: "5px 2px"
}} onChange={(e) => {
onModuleClicked(user, e.target.value)
}}>
<option value={"Programmieren"}>Programmieren</option>
<option value={"BWL"}>BWL</option>
<option value={"Lineare Algebra"}>Lineare Algebra</option>
<option value={"Analysis"}>Analysis</option>
<option value={"AnwendungsProjekt"}>AnwendungsProjekt</option>
</select>
</tr>
))} ))}
</select>
</td>
</tr>
))
}
</tbody> </tbody>
</table> </table>
</div> </div>
<div id="buttons">
<Button color="rgba(54,54,54,0.64)" width="100px" height="30px" text="Abbrechen" onClick={() => { <div style={{
router.back() display: "flex",
}}/> justifyContent: "flex-end",
<Button color="#77932b" width="100px" height="30px" text="Speichern" onClick={() => { alignItems: "center",
onCreateClicked() width: "100%",
}}/> gap: 10
}}>
<Button text={"Abbrechen"} onClick={onButtonAbort}/>
<Button text={"Speichern"} color={"#77932b"} onClick={onButtonSave}/>
</div> </div>
</div> </div>
</> </>
+12 -2
View File
@@ -3,10 +3,11 @@ import Button from "@/components/Button";
import {NextResponse} from "next/server"; import {NextResponse} from "next/server";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import {baseURL} from "@/components/Constants";
export default function Login() { export default function Login() {
let url = "http://localhost:8080/users" let url = baseURL + "/users"
async function on_login_click() { async function on_login_click() {
url += "?mail=" + inputUserName + "&password=" + inputPassword; url += "?mail=" + inputUserName + "&password=" + inputPassword;
@@ -20,7 +21,15 @@ export default function Login() {
if (value != "failed") { if (value != "failed") {
localStorage.setItem("sessionid", value); localStorage.setItem("sessionid", value);
url = baseURL + "/users/check?sessionid=" + value;
fetch(url).then(r => r.json()).then(u => localStorage.setItem("userid", u.id))
let admin = 0
await fetch(url).then(o => o.json()).then(user => {
admin = user.permissions})
localStorage.setItem("admin", admin)
if(admin === 1) {
await router.push("/semesteroverview") await router.push("/semesteroverview")
}else await router.push("/semesteroverviewLecturer")
} else { } else {
setInputPassword(""); setInputPassword("");
@@ -35,6 +44,7 @@ export default function Login() {
const [backgroundColor, setBackgroundColor] = useState("rgb(255, 255, 255)") const [backgroundColor, setBackgroundColor] = useState("rgb(255, 255, 255)")
const router = useRouter() const router = useRouter()
return ( return (
// <div className="border"> // <div className="border">
<login className={"login-container box-shadow"}> <login className={"login-container box-shadow"}>
@@ -42,7 +52,7 @@ export default function Login() {
<div className={"placement"}> <div className={"placement"}>
<br/> <br/>
<p className={"font-kinda-big"}>Username</p> <p className={"font-kinda-big"}>Username</p>
<input type="text" value={inputUserName} onChange={e => setInputUserName(e.target.value)} <input type="text" value={inputUserName} onChange={e => setInputUserName(e.target.value.toLowerCase())}
placeholder={hint} className="input input-bordered input-sm w-full max-w-xs box-shadow" placeholder={hint} className="input input-bordered input-sm w-full max-w-xs box-shadow"
style={{ style={{
backgroundColor: backgroundColor backgroundColor: backgroundColor
+29
View File
@@ -0,0 +1,29 @@
import Button from "@/components/Button";
import {useRouter} from "next/router";
import {baseURL} from "@/components/Constants";
export default function Logout()
{
const router = useRouter()
async function logout()
{
let url = baseURL + "/users/logout?sessionid=" + localStorage.getItem("sessionid");
await fetch(url)
await router.push("/")
}
return (
<div style={{
position: "absolute",
right: 20,
top: 20,
width: 130,
height: 60,
borderBottomRightRadius: 10,
}}>
<Button onClick={() => logout()} text={"Logout"} color={"#77932b"} width={100} height={40}/>
</div>
)
}
+26 -6
View File
@@ -5,24 +5,44 @@ import {deleteItem, editItem} from "@/components/Icons";
export default function SemesterTile(p) export default function SemesterTile(p)
{ {
let editable = true;
let color = "#ffffff"
if (p.color != null)
{
color = p.color;
}
if (p.editable != null)
{
editable = p.editable
}
useEffect(() => useEffect(() =>
{ {
window.addEventListener("contextmenu", (e) => (e.preventDefault())) window.addEventListener("contextmenu", (e) => (e.preventDefault()))
}) })
return ( return (
<div onClick={(e) => p.onClick(e)} className={"semester-tile box-shadow"}> <div
<p>{p.text}</p> style={{
<StatusBar progress={0}/>
<div style={{
display: "flex", display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
backgroundColor: "rgba(0,0,0,0)"
}}
onClick={(e) => p.onClick(e)}>
<p className={"semester-tile-p"} style={{
}}>{p.text}</p>
<p className={"semester-tile-p"} style={{
color: "gray"
}}>{p.text2}</p>
<div style={{
display: editable ? "flex" : "none",
flexDirection: "row", flexDirection: "row",
justifyContent: "center", justifyContent: "center",
alignItems: "center", alignItems: "center",
gap: 5 gap: 5
}}> }}>
<Button icon={deleteItem} width={30} height={30} color={"#ffffff"} onClick={p.onButtonDeleteClick}/>
<Button icon={editItem} width={30} height={30} color={"#ffffff"} onClick={p.onButtonEditClick}/>
</div> </div>
</div> </div>
) )
+21
View File
@@ -0,0 +1,21 @@
import Button from "@/components/Button";
import { baseURL } from "@/components/Constants";
import {useRouter} from "next/router";
export default function SubmitButton() {
const router = useRouter();
return (
<div
style={{
position: "absolute",
right: 70,
bottom: 20,
borderBottomRightRadius: 10,
}}
>
<Button onClick={() => router.push("/submit")} text={"Abgeben"} color={"#77932b"} width={100} height={40} />
</div>
);
}
@@ -0,0 +1,56 @@
import {baseURL} from "@/components/Constants";
import Button from "@/components/Button";
export default function SubmitWarning(p){
async function submit() {
let url = baseURL + "/module?sessionid=" + localStorage.getItem("sessionid");
let json1 = {
"id": 0,
"userid": localStorage.getItem("userid"),
"semesterid": localStorage.getItem("currentsid"),
"name": localStorage.getItem("currentmodulename"),
"activated": 0
}
await fetch(url, {
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(json1)
})
p.onClick();
p.onClick();
}
return (
<div className="box-shadow" style={{
position: "absolute",
top: 300,
left: 0,
right: 0,
borderRadius: 5,
textAlign: "center",
fontSize: 20,
margin: "auto",
width: 600
}}>
<p style={{paddingTop: 20, paddingBottom: 5}}>Möchten Sie wirklich abgeben?</p>
<p>Danach können Sie keine Änderungen mehr vornehmen!</p>
<div style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
paddingTop: 40,
paddingBottom: 20
}}>
<Button onClick={() => submit()} text={"Bestätigen"} color={"#77932b"} width={100} height={40} />
<div style={{width: 20}}></div>
<Button onClick={() => p.onClick()} text={"Abbrechen"} color={"red"} width={100} height={40} />
</div>
</div>
)
}
+5 -5
View File
@@ -6,14 +6,14 @@ import { useState } from 'react'
export default function WeekSelector(){ export default function WeekSelector(p){
const [weeks, setWeeks] = useState(0)
return ( return (
<> <>
<div className="weekSelector"> <div className="weekSelector">
<Button icon={arrowLeft} onClick={() => setWeeks(weeks-1)} /> <Button icon={arrowLeft} onClick={() => p.onFunctionLeft()} width={50} color={"#346991"}/>
<DateElement week={weeks}/> <DateElement year={p.year} startday={p.startday}/>
<Button icon={arrowRight} onClick={() => setWeeks(weeks+1)}/> <Button icon={arrowRight} onClick={() => p.onFunctionRight()} width={50} color={"#346991"}/>
</div> </div>
</> </>
) )
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+1
View File
@@ -1,5 +1,6 @@
import '@/styles/globals.css' import '@/styles/globals.css'
import '@/styles/calendarSideBar.css' import '@/styles/calendarSideBar.css'
import '@/styles/helppage.css'
export default function App({ Component, pageProps }) { export default function App({ Component, pageProps }) {
return <Component {...pageProps} /> return <Component {...pageProps} />
@@ -0,0 +1,20 @@
export default function BrowserNotSupported(p)
{
return (
<div style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}} >
<p style={{
fontSize: 40,
color: "red"
}}>Sorry but your browser is not supported right now</p>
<p style={{
fontSize: 30
}}>We recommend using Microsoft Edge or Google Chrome</p>
</div>
)
}
+3
View File
@@ -1,13 +1,16 @@
import InputForm from "@/components/InputForm"; import InputForm from "@/components/InputForm";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import Logout from "@/components/Logout";
export default function CreateSemester() export default function CreateSemester()
{ {
const router = useRouter(); const router = useRouter();
let {courseName, startDate, endDate} = router.query; let {courseName, startDate, endDate} = router.query;
return ( return (
<div className={"normal-centered"}> <div className={"normal-centered"}>
<Logout/>
<InputForm startDate={startDate} endDate={endDate} courseName={courseName}/> <InputForm startDate={startDate} endDate={endDate} courseName={courseName}/>
</div> </div>
) )
+97
View File
@@ -0,0 +1,97 @@
import Background from "@/components/Background";
import Back from "@/components/Back";
import {useRouter} from "next/router";
import screen1 from "@/images/screen1.png"
import screen2 from "@/images/screen2.png"
import screen3 from "@/images/screen3.png"
import screen4 from "@/images/screen4.png"
import screen5 from "@/images/screen5.png"
import screen6 from "@/images/screen6.png"
import screen7 from "@/images/screen7.png"
export default function Help(p)
{
const router = useRouter()
return (
<div>
<div className={"help-line"}>
<img src={screen1.src}/>
<div className={"text-form"}>
<h1>Die Monats-Seiten-Leiste</h1>
<p>- Hier kannst du sehen in welchem Monat du dich aktuell befindest (blau hinterlegt).</p>
<p>- Durch einen Links-Klick auf eine Monatskacheln kannst du direkt an den Anfang dieses Monats springen</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen2.src}/>
<div className={"text-form"}>
<h1>Die Planungs-Ansicht</h1>
<p>- Hier siehst du alle deine Termine in grün (bzw. gelb bei Warnungen) und von anderen Dozenten in grau</p>
<p>- Durch einen Links-Klick kannst du eine neue Vorlesung an einem Tag erstellen</p>
<p>- Durch Halten der dunkleren Leisten kannst du die Zeiten des Termins anpassen</p>
<p>- Durch Rechts-Klick kannst du eine Vorlesung löschen</p>
<p>- Durch Klicken auf die Pfeiltasten oben kannst du die Woche wechseln</p>
<p>- Bitte beachte, dass du Vorlesungen nur zwischen den beiden Roten linien erstellen kannst</p>
<p>- Ausgegraute Tage liegen nicht im Semester, hier kannst du nicht planen</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen3.src}/>
<div className={"text-form"}>
<h1>Die Warnungs-Ansicht</h1>
<p>- Sollte ein Termin gelb erscheinen kannst du hier sehen woran das liegt</p>
<p>- Warnung sind empfohlene Verbesserungsverschläge aber müssen nicht zwangshaft beachtet werden</p>
<p>- Sollte hier "Okay" für einen Tag stehen ist alles perfekt</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen5.src}/>
<div className={"text-form"}>
<h1>Der Login</h1>
<p>- Hier kannst du dich mit deiner Email und deinem Passwort einloggen</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen4.src}/>
<div className={"text-form"}>
<h1>Der Logout</h1>
<p>- Über diesen Button kannst du dich ausloggen</p>
<p>- Loggst du dich nicht selbst aus, wirst du nach 2 Stunden automatisch ausgeloggt</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen6.src}/>
<div className={"text-form"}>
<h1>Das Dashboard</h1>
<h2>Für Admins:</h2>
<p>- Über den "+" Knopf kannst du ein neues Semester erstellen</p>
<p>- Über den Stift kannst du ein bestehendes Semester editieren</p>
<p>- Über den Mülleimer kannst du ein bestehndes Semester löschen</p>
<h2>Für Dozenten (und Admins):</h2>
<p>- Hier siehst du deine Semester mit den jeweiligen Modulen</p>
<p>- Sollte ein Semester bei dir Ausgegraut sein, wurdest du für dieses schon gewählt aber noch nicht freigeschalten</p>
<p>- Duch einen Links-Klick auf ein weises Semester kann in die Planungsübersicht gewechselt werden</p>
</div>
</div>
<div className={"help-line"}>
<img src={screen7.src}/>
<div className={"text-form"}>
<h1>Semester erstellen / bearbeiten</h1>
<p>- Hier kannst du alle daten wie Name, Start- und Endzeitpunkt eines Semesters eintragen</p>
<p>- Du kannst einen Dozenten "wählen" d.h. er soll in diesem Semester dozieren</p>
<p>- Jedem Dozenten kannst du ein Modul zuordnen, welches er dozieren soll</p>
<p>- Sobald du die Schaltfläche "Freischalten" aktiviert hast, kann der Dozent mit der eigenständigen Planung beginnen.</p>
<p>- Jeder genannte Schritt, insbesondere der Letzte kann auch nachträglich im Bearbeitungsmodus ausgeführt werden</p>
</div>
</div>
</div>
)
}
+15 -12
View File
@@ -1,29 +1,32 @@
import {Inter} from 'next/font/google' import {Inter} from 'next/font/google'
import React, {useState} from "react"; import React, {useEffect, useState} from "react";
import StatusBar from "@/components/StatusBar";
import Button from "@/components/Button";
import {arrowLeft, arrowRight} from "@/components/Icons";
import WeekSelector from "@/components/WeekSelector";
import PopUp from "@/components/PopUp";
import CalenderView from "@/components/CalenderView";
import DateElement from "@/components/DateElement";
import InputForm from "@/components/InputForm";
import Login from "@/components/Login"; import Login from "@/components/Login";
import Test from "@/components/Test";
import BasicDateCalendar from "@/components/CalendarSideBar";
import {randomInt} from "next/dist/shared/lib/bloom-filter/utils";
import Background from "@/components/Background"; import Background from "@/components/Background";
import {useRouter} from "next/router";
import HelpButton from "@/components/HelpButton";
const inter = Inter({subsets: ['latin']}) const inter = Inter({subsets: ['latin']})
export default function Home(p) { export default function Home(p) {
const router = useRouter()
useEffect(() => {
let isEdge = window.navigator.userAgent.indexOf("Edg") > -1
let isChrome = window.navigator.userAgent.indexOf("Chrome") > -1
if(!(isEdge || isChrome))
{
router.push("/browserNotSupported")
}
})
return ( return (
<div className={"normal-centered"}> <div className={"normal-centered"}>
<Background/> <Background/>
<HelpButton/>
<h1 style={{ <h1 style={{
fontSize: 40, fontSize: 40,
fontWeight: "bold", fontWeight: "bold",
+25
View File
@@ -0,0 +1,25 @@
import CalenderView from "@/components/CalenderView";
import Background from "@/components/Background";
import Logout from "@/components/Logout";
import Back from "@/components/Back";
import BasicDateCalendar from "@/components/CalendarSideBar";
import {useRouter} from "next/router";
import HelpButton from "@/components/HelpButton";
import SubmitButton from "@/components/SubmitButton";
export default function planning(p)
{
let router = useRouter()
return (
<div className={"normal-centered"}>
<Logout/>
<Back onClick={() => router.back()}/>
<HelpButton/>
<Background/>
<CalenderView/>
<SubmitButton />
</div>
)
}
+58 -29
View File
@@ -5,53 +5,52 @@ import InputForm from "@/components/InputForm";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import PopUp from "@/components/PopUp"; import PopUp from "@/components/PopUp";
import Background from "@/components/Background"; import Background from "@/components/Background";
import Logout from "@/components/Logout";
import {baseURL} from "@/components/Constants";
import HelpButton from "@/components/HelpButton";
import StatusBar from "@/components/StatusBar";
import {deleteItem, editItem} from "@/components/Icons";
export default function SemesterOverview(p) {
async function getSemesters() {
let urlTest = baseURL + "/semester/all?sessionid=" + localStorage.getItem("sessionid");
export default function SemesterOverview(p)
{
async function getSemesters()
{
let urlTest = "http://localhost:8080/semester/all?sessionid=" + localStorage.getItem("sessionid");
await fetch(urlTest).then(response => response.json()).then(s => { await fetch(urlTest).then(response => response.json()).then(s => {
setEntries(s) setEntries(s)
}) })
} }
function onClickSemester(e, m) function onClickSemester(e, m) {
{ if (m.target === m.currentTarget) {
if(m.target === m.currentTarget)
{
localStorage.setItem("currentsid", e.id) localStorage.setItem("currentsid", e.id)
} router.push("/planning")
} }
function onClickNewSemester() }
{
function onClickNewSemester() {
localStorage.setItem("currentsid", 0);
router.push("/createSemester"); router.push("/createSemester");
} }
function togglePopup() function togglePopup() {
{ if (modalDisplay === "block") {
if(modalDisplay === "block")
{
setModalDisplay("none"); setModalDisplay("none");
} } else {
else
{
setModalDisplay("block"); setModalDisplay("block");
} }
} }
function funcButtonAbort() function funcButtonAbort() {
{
togglePopup(); togglePopup();
} }
async function funcButtonDelete() async function funcButtonDelete() {
{
let id = localStorage.getItem("currentsid"); let id = localStorage.getItem("currentsid");
let url = "http://localhost:8080/semester?sessionid=" + localStorage.getItem("sessionid") + "&id=" + id; let url = baseURL + "/semester?sessionid=" + localStorage.getItem("sessionid") + "&id=" + id;
await fetch(url, { await fetch(url, {
method: "DELETE" method: "DELETE"
}); });
@@ -60,8 +59,7 @@ export default function SemesterOverview(p)
getSemesters(); getSemesters();
} }
async function funcButtonEdit(e, m) async function funcButtonEdit(e, m) {
{
localStorage.setItem("currentsid", e.id); localStorage.setItem("currentsid", e.id);
let semester = e; let semester = e;
@@ -76,15 +74,21 @@ export default function SemesterOverview(p)
await router.push({ await router.push({
pathname: "/createSemester", pathname: "/createSemester",
query: {courseName: semester.name, startDate: startDate.toISOString().slice(0, 10), endDate: endDate.toISOString().slice(0, 10)}, query: {
courseName: semester.name,
startDate: startDate.toISOString().slice(0, 10),
endDate: endDate.toISOString().slice(0, 10)
},
}); });
getSemesters(); getSemesters();
} }
useEffect(() => { useEffect(() => {
getSemesters(); getSemesters();
}, []) }, [])
const [entries, setEntries] = useState([]) const [entries, setEntries] = useState([])
const [modalDisplay, setModalDisplay] = useState("none"); const [modalDisplay, setModalDisplay] = useState("none");
const [modalHint, setModalHint] = useState(""); const [modalHint, setModalHint] = useState("");
@@ -92,16 +96,41 @@ export default function SemesterOverview(p)
return ( return (
<div className={"semester-overview"}> <div className={"semester-overview"}>
<Logout/>
<HelpButton/>
<Background/> <Background/>
{ {
entries.map(e => (<SemesterTile text={e.name} onClick={(f) => onClickSemester(e, f)} onButtonDeleteClick={() => { entries.map(e => (
<div className={"semester-tile box-shadow"} onClick={(f) => onClickSemester(e, f)}>
<SemesterTile text={e.name} onClick={(f) => onClickSemester(e, f)} onButtonDeleteClick={() => {
localStorage.setItem("currentsid", e.id) localStorage.setItem("currentsid", e.id)
setModalHint(e.name + " Löschen?"); setModalHint(e.name + " Löschen?");
togglePopup(); togglePopup();
}} onButtonEditClick={(m) => { }} onButtonEditClick={(m) => {
localStorage.setItem("currentsid", e.id) localStorage.setItem("currentsid", e.id)
funcButtonEdit(e, m); funcButtonEdit(e, m);
}}/>)) }}/>
<StatusBar progress={0}/>
<div style={
{
display:"flex",
justifyContent:"center",
alignItems:"center"
}
}>
<Button icon={deleteItem} width={30} height={30} color={"#ffffff"}
onClick={(m) => {
localStorage.setItem("currentsid", e.id)
setModalHint(e.name + " Löschen?");
togglePopup()
}}/>
<Button icon={editItem} width={30} height={30} color={"#ffffff"}
onClick={(m) => {
localStorage.setItem("currentsid", e.id)
funcButtonEdit(e, m)
}}/>
</div>
</div>))
} }
<Button color={"#dcdcdc"} text={"+"} width={240} height={160} fontColor={"black"} fontSize={50} <Button color={"#dcdcdc"} text={"+"} width={240} height={160} fontColor={"black"} fontSize={50}
onClick={() => onClickNewSemester()}/> onClick={() => onClickNewSemester()}/>
@@ -0,0 +1,75 @@
import React, {useEffect, useState} from "react";
import SemesterTile from "@/components/SemesterTile";
import {useRouter} from "next/router";
import Background from "@/components/Background";
import Logout from "@/components/Logout";
import {baseURL} from "@/components/Constants"
import HelpButton from "@/components/HelpButton";
import StatusBar from "@/components/StatusBar";
export default function SemesteroverviewLecturer(p) {
function getModules() {
let urlTest = baseURL + "/module/id?sessionid=" + localStorage.getItem("sessionid");
fetch(urlTest).then(response => response.json()).then(m => {
setEntries(m);
let args = "";
for (let i = 0; i < m.length; i++) {
args += m[i].semesterid;
if (i < m.length - 1) {
args += "a";
}
}
let temp = []
let semesterURL = baseURL + "/semester/id/all?ids=" + args + "&sessionid=" + localStorage.getItem("sessionid");
fetch(semesterURL).then(r => r.json()).then(sem => {
sem.map(e => {
temp.push(e.name)
})
}).then(() => setSemesterNames(temp))
})
}
function onClickSemester(e, m) {
if (e.activated == 1) {
if (m.target === m.currentTarget) {
localStorage.setItem("currentsid", e.semesterid)
localStorage.setItem("currentmodulename", e.name)
localStorage.setItem("moduleid", e.id)
router.push("/planning")
}
}
}
useEffect(() => {
getModules();
}, [])
const [entries, setEntries] = useState([]);
const [semesterNames, setSemesterNames] = useState([]);
const router = useRouter();
return (
<div className={"semester-overview"}>
<Logout/>
<Background/>
<HelpButton/>
{entries.map((e, index) => (
<div className={"semester-tile box-shadow"} style={{
backgroundColor: e.activated == 1 ? "#ffffff" : "#aaaaaa"
}} onClick={(f) => onClickSemester(e, f)}>
<SemesterTile
editable={false} text={semesterNames[index]} text2={e.name}
onClick={(f) => onClickSemester(e, f)}
/>
<StatusBar progress={0}/>
</div>
))}
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import Logout from "@/components/Logout";
import SubmitWarning from "@/components/SubmitWarning";
import Back from "@/components/Back";
import {useRouter} from "next/router";
import Background from "@/components/Background";
export default function Submit(){
const router = useRouter();
return(
<div>
<Background />
<Logout />
<SubmitWarning onClick={() => router.back()}/>
<Back onClick={() => router.back()}/>
</div>
)
}
+43 -15
View File
@@ -1,19 +1,16 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.A .A
{ {
border: 2px solid; border: 0px solid;
border-color: black;
border-radius: 20px; border-radius: 20px;
margin: 2px; margin: 10px;
background: linear-gradient(to bottom, #FFC1C1, #CD3333); background-color: white;
padding: 15px;
height: 270px;
}
.A P
{
text-align: center;
} }
.Days .Days
@@ -21,8 +18,8 @@ body {
display: inline-grid; display: inline-grid;
grid-template-columns: repeat(7, 1fr); grid-template-columns: repeat(7, 1fr);
grid-template-rows: repeat(5, 1fr); grid-template-rows: repeat(5, 1fr);
height: 50%; height: 200px;
width: 100%; width: 250px;
} }
.Down .Down
@@ -33,3 +30,34 @@ body {
height: 200%; height: 200%;
width: 20%; width: 20%;
} }
@media only screen and (min-width: 1650px)
{
.Allround
{
position: relative;
max-height : 73vh;
overflow-y: scroll;
overflow-anchor: none;
}
.Allround::-webkit-scrollbar
{
background-color: rgba(0, 0, 0, 0);
width: 12px;
}
.Allround::-webkit-scrollbar-thumb
{
background-color: gray;
border-radius: 15px;
}
}
@media only screen and (max-width: 1650px)
{
.Allround
{
display: none;
}
}
+113 -111
View File
@@ -13,6 +13,18 @@ body {
} }
::-webkit-scrollbar
{
background-color: rgba(0, 0, 0, 0);
width: 12px;
}
::-webkit-scrollbar-thumb
{
background-color: gray;
border-radius: 15px;
}
.splash { .splash {
position: absolute; position: absolute;
border-radius: 70px; border-radius: 70px;
@@ -61,6 +73,48 @@ body {
box-shadow: 0 0 10px rgba(0, 0, 0,1); box-shadow: 0 0 10px rgba(0, 0, 0,1);
} }
/*
Input Form
*/
.input-form
{
width: 600px;
background-color: white;
padding: 30px;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: flex-start;
gap: 20px;
}
table
{
width: 550px;
}
.table-wrapper
{
max-height: 40%;
overflow-y: scroll;
}
td
{
text-align: center;
}
.input-form p, .input-form th
{
font-size: 18px;
font-weight: bold;
color: #5e5e5e;
}
/* /*
Button Button
*/ */
@@ -105,6 +159,7 @@ Step Progress Bar
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
max-width: 400px; max-width: 400px;
pointer-events: none;
} }
.steps { .steps {
@@ -115,6 +170,7 @@ Step Progress Bar
gap: 20px; gap: 20px;
width: 100%; width: 100%;
position: relative; position: relative;
pointer-events: none;
} }
.step { .step {
@@ -126,6 +182,7 @@ Step Progress Bar
justify-content: center; justify-content: center;
color: white; color: white;
font-weight: bold; font-weight: bold;
pointer-events: none;
} }
.steps .not-started { .steps .not-started {
@@ -165,17 +222,23 @@ weekSelector
.dateElement { .dateElement {
display: flex; display: flex;
max-width: 900px;
width: 900px;
margin-left: 20px; margin-left: 20px;
margin-right: 20px; margin-right: 20px;
height: 50px;
width: 200px;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
background-color: #0d52ce; font-weight: bold;
color: black;
font-size: 20px;
} }
.weekSelector { .weekSelector {
height: 13vh;
display: flex; display: flex;
padding: 5px 5px;
background-color: rgba(0, 0, 0, 0);
border-radius: 10px;
} }
/* /*
@@ -235,7 +298,7 @@ Popup
display: flex; display: flex;
flex-direction: row; flex-direction: row;
width: 100%; width: 100%;
justify-content: end; justify-content: flex-end;
gap: 5px; gap: 5px;
} }
@@ -243,16 +306,46 @@ Popup
Calender View Calender View
*/ */
@media (max-width: 1300px) {
.error-bar
{
display: none;
}
}
@media (min-width: 1300px) {
.error-bar
{
width: 250px;
border-radius: 15px;
height: 73vh;
max-height: 73vh;
overflow-y: scroll;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
gap: 10px;
}
}
.calender-direction-wrapper
{
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.calender-container { .calender-container {
max-height: 600px; position: relative;
max-height: 60vh;
overflow-y: scroll; overflow-y: scroll;
overflow-anchor: none;
display: grid; display: grid;
} }
.calender-container::-webkit-scrollbar {
display: none;
}
.content { .content {
grid-area: 1 / 1; grid-area: 1 / 1;
@@ -276,34 +369,33 @@ Calender View
width: 1000px; width: 1000px;
gap: 5px; gap: 5px;
padding: 0 0 5px 0; padding: 0 0 5px 0;
background-color: #363636;
} }
.calender-view { .calender-view {
width: 1000px; width: 1000px;
height: 2400px; height: 2400px;
background-color: #363636;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
align-items: stretch; align-items: stretch;
justify-content: stretch; justify-content: stretch;
gap: 5px; gap: 5px;
user-select: none; user-select: none;
padding: 2px 0 0 0; padding: 0;
} }
.calender-view .spalte { .calender-view .spalte {
border-radius: 10px; border-radius: 10px;
width: 400px; width: 400px;
background-color: white; /*background-color: #ffffff;*/
display: grid; display: grid;
padding: 0 3px; padding: 0 3px;
grid-template-columns: 100%; grid-template-columns: 100%;
background-color: white;
} }
.wochen-tag-container .wochen-tag { .wochen-tag-container .wochen-tag {
text-align: center; text-align: center;
background-color: #f80000; background-color: #346991;
width: 400px; width: 400px;
color: white; color: white;
border-radius: 10px; border-radius: 10px;
@@ -322,7 +414,7 @@ Calender View
justify-content: space-between; justify-content: space-between;
padding: 0 2px; padding: 0 2px;
align-items: center; align-items: center;
cursor: move; /*cursor: move;*/
z-index: 10; z-index: 10;
overflow: hidden; overflow: hidden;
margin-top: 1px; margin-top: 1px;
@@ -330,7 +422,7 @@ Calender View
} }
.entry .resize-grab { .entry .resize-grab {
height: 5px; height: 6px;
cursor: ns-resize; cursor: ns-resize;
width: 100%; width: 100%;
} }
@@ -341,101 +433,9 @@ Calender View
font-size: 16px; font-size: 16px;
cursor: default; cursor: default;
pointer-events: none; pointer-events: none;
}
/*
inputForm
*/
input {
border-width: 2px;
border-radius: 5px;
}
.courseNameInput {
width: 300px;
padding: 5px;
border: none;
background-color: white;
border-radius: 5px;
font-family: Arial, serif;
}
.selector
{
border-width: 0;
border-radius: 10px;
}
.semesterDateInput {
width: 150px;
padding: 5px;
border: none;
background-color: white;
border-radius: 5px;
font-family: Arial, serif;
}
.semesterDateLables, .semesterDateInputPair {
display: flex;
flex-direction: row;
justify-content: left;
padding: 0;
border: none;
background-color: white;
border-radius: 5px;
}
.inputFieldSeperator {
width: 40px;
text-align: center; text-align: center;
} }
.semesterDateLable {
margin-right: 32px;
}
.semesterRangeInput {
margin-top: 50px;
}
.inputForm {
width: 600px;
height: 600px;
padding: 20px;
/*border: solid;*/
border-radius: 10px;
display: flex;
flex-direction: column;
background-color: white;
}
#buttons {
align-self: flex-end;
display: flex;
flex-direction: row;
align-items: flex-end;
gap: 10px;
}
.dozentSelector {
height: 350px;
/*border: solid;*/
margin-top: 20px;
width: 500px;
padding: 10px;
margin-bottom: 20px;
}
th {
text-align: left;
padding: 0 10px;
}
td {
padding: 0 10px;
}
/* /*
Login Login
*/ */
@@ -503,7 +503,6 @@ SemesterTile
*/ */
.semester-tile { .semester-tile {
background-color: #ffffff;
width: 240px; width: 240px;
height: 160px; height: 160px;
color: black; color: black;
@@ -514,18 +513,21 @@ SemesterTile
justify-content: center; justify-content: center;
font-size: 20px; font-size: 20px;
gap: 10px; gap: 10px;
background-color: white;
} }
.semester-tile:hover { .semester-tile:hover {
background-color: #e1e1e1; background-color: #e1e1e1;
} }
.semester-tile p { .semester-tile-p {
pointer-events: none; pointer-events: none;
font-weight: bold; font-weight: bold;
font-size: 23px; font-size: 23px;
} }
.semester-tile .step-container {
pointer-events: none; .Error
{
} }
+31
View File
@@ -0,0 +1,31 @@
.help-line
{
padding: 30px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 50px;
}
.text-form
{
display: flex;
flex-direction: column;
justify-content: flex-start;
height: 100%;
}
.text-form h1
{
font-size: 30px;
}
.text-form p
{
font-size: 20px;
}
.text-form h2
{
font-size: 26px;
}
Binary file not shown.
+200758 -124770
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,26 +1,21 @@
package com.example.backend.anwprj; package com.example.backend.anwprj.Database;
import com.example.backend.anwprj.Encryption.RSA; import com.example.backend.discard.Encryption.RSA;
import com.example.backend.anwprj.Days.Day;
import com.example.backend.anwprj.Entries.Entry; import com.example.backend.anwprj.Entries.Entry;
import com.example.backend.anwprj.Semesters.Semester; import com.example.backend.anwprj.Semesters.Semester;
import com.example.backend.anwprj.Users.User; import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Week.Week;
import com.example.backend.anwprj.Module.Module; import com.example.backend.anwprj.Module.Module;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DataBaseHandler public class DataBaseHandler {
{
//singleton instance of database handler //singleton instance of database handler
private static DataBaseHandler instance = null; private static DataBaseHandler instance = null;
public static DataBaseHandler getInstance() public static DataBaseHandler getInstance() {
{ if (instance == null) {
if (instance == null)
{
instance = new DataBaseHandler(); instance = new DataBaseHandler();
} }
@@ -33,299 +28,219 @@ public class DataBaseHandler
private Statement st; private Statement st;
private boolean encrypted = false; private boolean encrypted = false;
public DataBaseHandler() public DataBaseHandler() {
{ try {
try
{
//connect to the local database //connect to the local database
connection = DriverManager.getConnection("jdbc:h2:./database", "adm", "73bgjfdsfJ!934"); connection = DriverManager.getConnection("jdbc:h2:./database", "adm", "73bgjfdsfJ!934");
st = connection.createStatement(); st = connection.createStatement();
} catch (SQLException e) } catch (SQLException e) {
{
e.printStackTrace(); e.printStackTrace();
System.out.println("No Connection!");
} }
} }
/** /**
* WEEKS * ENTRIES
*/ */
public void addEntry(Entry entry) {
try {
st.executeUpdate("insert into entries (daynumber, yearnumber, semesterid, usercreatedbyid, timestart, timeend, info) values (" +
entry.getDaynumber() + ", " + entry.getYearnumber() + ", " + entry.getSemesterid() + ", " +
entry.getUsercreatedbyid() + ", " + entry.getTimestart() + ", " + entry.getTimeend() + ", '" + entry.getInfo() + "')"
);
} catch (Exception e) {
e.printStackTrace();
}
}
public Week addWeek(Week week) public Entry[][] getEntries(int semesterid, int daynumber, int yearnumber) {
{ try {
try ResultSet rs = st.executeQuery("select * from entries where " +
{ "semesterid=" + semesterid +
st.executeUpdate("insert into weeks (semesterid, weeknumber) values (" + week.getSemesterid() + ", " + week.getWeeknumber() + ")"); " and yearnumber=" + yearnumber +
" and daynumber between " + daynumber + " and " + daynumber + 6);
return getWeek(week.getSemesterid(), week.getWeeknumber()); List<Entry> entryList = new ArrayList<>();
Entry current = null;
while ((current = resultSetToEntry(rs)) != null) {
entryList.add(current);
}
} catch (SQLException e) Entry[][] entries = new Entry[6][20];
{ for (int i = 0; i < 6; i++) {
int f = 0;
for (int j = 0; j < entryList.size(); j++) {
if (entryList.get(j).getDaynumber() == i + daynumber) {
entries[i][f] = entryList.get(j);
f++;
}
}
}
return entries;
} catch (Exception e) {
return null; return null;
} }
} }
public Week getWeek(int id)
{
ResultSet rs = null;
try
{
rs = st.executeQuery("select * from weeks where id=" + id);
return resultSetToWeek(rs); public Entry[][] getAllEntrys(int semesterid, int daynumber, int yearnumber, int userid) {
try {
ResultSet rs = st.executeQuery("select * from entries where " +
"semesterid<>" + semesterid +
" and yearnumber=" + yearnumber +
" and usercreatedbyid=" + userid +
" and daynumber between " + daynumber + " and " + daynumber + 6);
List<Entry> entryList = new ArrayList<>();
Entry current = null;
while ((current = resultSetToEntry(rs)) != null) {
entryList.add(current);
}
Entry[][] entries = new Entry[6][20];
for (int i = 0; i < 6; i++) {
int f = 0;
} catch (SQLException e) for (int j = 0; j < entryList.size(); j++) {
if (entryList.get(j).getDaynumber() == i + daynumber) {
{ entries[i][f] = entryList.get(j);
f++;
}
}
}
return entries;
} catch (Exception e) {
return null; return null;
} }
} }
public Week getWeek(int semesterid, int weeknumber) public Entry[] getAllEntries(int semesterid, int userid) {
{ try {
try ResultSet rs = st.executeQuery("select * from entries where " +
{ "semesterid=" + semesterid +
ResultSet rs = st.executeQuery("select * from weeks where semesterid =" + semesterid + " and weeknumber=" + weeknumber); " and usercreatedbyid=" + userid);
List<Entry> entriestate = new ArrayList<>();
return resultSetToWeek(rs); Entry current = null;
while ((current = resultSetToEntry(rs)) != null) {
entriestate.add(current);
} }
catch (SQLException e) return entriestate.toArray(new Entry[0]);
{ } catch (Exception e) {
return null; return null;
} }
} }
private Week resultSetToWeek(ResultSet rs) { public void deleteEntry(int id) {
try {
st.executeUpdate("delete from entries where id=" + id);
} catch (Exception e) {
}
}
public void updateEntry(Entry entry) {
try {
st.executeUpdate("update entries set timeend=" + entry.getTimeend() + ", timestart=" + entry.getTimestart() + " where id=" + entry.getId());
} catch (Exception e) {
}
}
public Entry resultSetToEntry(ResultSet rs) {
try { try {
rs.next(); rs.next();
return new Entry(
return new Week(
rs.getInt("id"), rs.getInt("id"),
rs.getInt("semesterid"), rs.getInt("daynumber"),
rs.getInt("weeknumber")
);
} catch (SQLException e) {
return null;
}
}
/**
DAYS
*/
public Day addDay(Day day)
{
try
{
st.executeUpdate("insert into days (dayinyear, yearnumber, semesterid) values (" + day.getDayinyear() + ", " + day.getYearnumber() + ", " + day.getSemesterid() + ")");
return getDay(day.getDayinyear(), day.getYearnumber(), day.getSemesterid());
} catch (SQLException e)
{
return null;
}
}
public Day getDay(int id)
{
try
{
ResultSet rs = st.executeQuery("select * from days where id=" + id);
return resultSetToDay(rs);
}
catch(Exception e)
{
return null;
}
}
public Day getDay(int dayinyear, int yearnumber, int semesterid)
{
try
{
ResultSet rs = st.executeQuery("select * from days where dayinyear =" + dayinyear + " and yearnumber =" + yearnumber + " and semesterid =" + semesterid);
return resultSetToDay(rs);
}
catch(Exception e)
{
return null;
}
}
private Day resultSetToDay(ResultSet rs)
{
try
{
rs.next();
return new Day(
rs.getInt("id"),
rs.getInt("dayinyear"),
rs.getInt("yearnumber"), rs.getInt("yearnumber"),
rs.getInt("semesterid")
);
} catch (SQLException e)
{
return null;
}
}
/**
ENTRIES
*/
//method that returns all entries of a day based on the given parameters
public Entry[] getEntries(int dayinweek, int weeknumber, int semesterid, User user)
{
try
{
//search the correct data in the database
ResultSet rs = st.executeQuery("select distinct e.id, e.dayid, e.usercreatedbyid, e.timestart, e.timeend, e.info " +
"from entries e, days d, weeks w, semester s " +
"where e.dayid = d.id and " +
"d.weekid = w.id and " +
"w.semesterid = s.id and " +
"d.dayinweek = " + dayinweek + " and " +
"w.weeknumber = " + weeknumber + " and " +
"s.id = " + semesterid);
int editable = 0;
//a temporary list to save entry objects in
List<Entry> temp = new ArrayList<>();
//while there a still entries for the day
while(rs.next())
{
editable = 0;
//if entry has been created by the requesting user set the entry to editable (or the user is admin)
if(rs.getInt("usercreatedbyid") == user.getId() || user.getPermissions() == 1)
{
editable = 1;
}
temp.add(
new Entry(
rs.getInt("id"),
rs.getInt("dayid"),
rs.getInt("usercreatedbyid"), rs.getInt("usercreatedbyid"),
rs.getInt("timestart"), rs.getInt("timestart"),
rs.getInt("timeend"), rs.getInt("timeend"),
rs.getString("info"), rs.getInt("semesterid"),
editable rs.getString("info")
)
); );
} } catch (Exception e) {
//return the temporary list as an array
return temp.toArray(new Entry[0]);
} catch (SQLException e)
{
throw new RuntimeException(e);
}
}
/**
SEMESTER
*/
//get a semester object by its name
public Semester getSemester(String name)
{
try
{
ResultSet rs = st.executeQuery("select * from SEMESTER where name = '" + name + "'");
return resultSetToSemester(rs);
}
catch(Exception e)
{
return null; return null;
} }
} }
public Semester getSemester(int id)
{ /**
try * SEMESTER
{ */
//get a semester object by its name
public Semester getSemester(String name) {
try {
ResultSet rs = st.executeQuery("select * from SEMESTER where name = '" + name + "'");
return resultSetToSemester(rs);
} catch (Exception e) {
return null;
}
}
public Semester getSemester(int id) {
try {
ResultSet rs = st.executeQuery("select * from semester where id=" + id); ResultSet rs = st.executeQuery("select * from semester where id=" + id);
return resultSetToSemester(rs); return resultSetToSemester(rs);
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
//write a new semester to the database returns if process was successful //write a new semester to the database returns if process was successful
public Semester addSemester(Semester s) public Semester addSemester(Semester s) {
{ try {
try st.executeUpdate("insert into SEMESTER (startday, endday, name, startyear, endyear, number) values (" + s.getStartday() + ", " + s.getEndday() + ", '" + s.getName() + "', " + s.getStartyear() + ", " + s.getEndyear() + ", " + s.getNumber() + ")");
{
st.executeUpdate("insert into SEMESTER (startday, endday, name, startyear, endyear) values (" + s.getStartday() + ", " + s.getEndday() + ", '" + s.getName() + "', " + s.getStartyear() + ", " + s.getEndyear() + ")");
return getSemester(s.getName()); return getSemester(s.getName());
} catch (Exception e) } catch (Exception e) {
{
return null; return null;
} }
} }
public Semester[] getAllSemesters() public Semester[] getAllSemesters() {
{ try {
try
{
ResultSet rs = st.executeQuery("select * from semester"); ResultSet rs = st.executeQuery("select * from semester");
List<Semester> semestersList = new ArrayList<>(); List<Semester> semestersList = new ArrayList<>();
Semester s = null; Semester s = null;
while((s = resultSetToSemester(rs)) != null) while ((s = resultSetToSemester(rs)) != null) {
{
semestersList.add(s); semestersList.add(s);
} }
return semestersList.toArray(new Semester[0]); return semestersList.toArray(new Semester[0]);
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
public Semester updateSemester(Semester semester) public Semester updateSemester(Semester semester) {
{ try {
try
{
st.executeUpdate("update semester set startday=" + semester.getStartday() + ", " + st.executeUpdate("update semester set startday=" + semester.getStartday() + ", " +
"endday=" + semester.getEndday() + ", " + "endday=" + semester.getEndday() + ", " +
"name='" + semester.getName() + "', " + "name='" + semester.getName() + "', " +
"startyear=" + semester.getStartyear() + ", " + "startyear=" + semester.getStartyear() + ", " +
"number=" + semester.getNumber() + ", " +
"endyear=" + semester.getEndyear() + " where id=" + semester.getId()); "endyear=" + semester.getEndyear() + " where id=" + semester.getId());
return getSemester(semester.getId()); return getSemester(semester.getId());
} catch (SQLException e) } catch (SQLException e) {
{
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public void deleteSemester(int id) public void deleteSemester(int id) {
{ try {
try st.executeUpdate("DELETE FROM modules WHERE semesterid=" + id);
{
st.executeUpdate("DELETE FROM modules WHERE semesterId = " + id);
st.executeUpdate("delete from semester where id=" + id); st.executeUpdate("delete from semester where id=" + id);
} } catch (Exception e) {
catch(Exception e)
{
} }
} }
public Semester resultSetToSemester(ResultSet rs) public Semester resultSetToSemester(ResultSet rs) {
{ try {
try
{
rs.next(); rs.next();
return new Semester( return new Semester(
rs.getInt("id"), rs.getInt("id"),
@@ -333,17 +248,16 @@ public class DataBaseHandler
rs.getInt("endday"), rs.getInt("endday"),
rs.getString("name"), rs.getString("name"),
rs.getInt("startyear"), rs.getInt("startyear"),
rs.getInt("endyear") rs.getInt("endyear"),
rs.getInt("number")
); );
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
/** /**
MODULE * MODULE
*/ */
//get a module object by its id //get a module object by its id
@@ -351,22 +265,17 @@ public class DataBaseHandler
try { try {
ResultSet rs = st.executeQuery("SELECT * FROM modules WHERE id=" + id); ResultSet rs = st.executeQuery("SELECT * FROM modules WHERE id=" + id);
return resultSetToModule(rs); return resultSetToModule(rs);
} } catch (Exception ex) {
catch (Exception ex) {
return null; return null;
} }
} }
public Module getModule(int userid, int semesterid, String name) public Module getModule(int userid, int semesterid) {
{ try {
try ResultSet rs = st.executeQuery("select * from modules where userid=" + userid + " and semesterid=" + semesterid);
{
ResultSet rs = st.executeQuery("select * from modules where userid=" + userid + " and semesterid=" + semesterid + " and name='" + name + "'");
return resultSetToModule(rs); return resultSetToModule(rs);
} } catch (Exception e) {
catch (Exception e)
{
return null; return null;
} }
} }
@@ -377,73 +286,64 @@ public class DataBaseHandler
ResultSet rs = st.executeQuery("SELECT * FROM modules WHERE userid = " + userid); ResultSet rs = st.executeQuery("SELECT * FROM modules WHERE userid = " + userid);
List<Module> moduleList = new ArrayList<>(); List<Module> moduleList = new ArrayList<>();
Module m = null; Module m = null;
while((m = resultSetToModule(rs)) != null) while ((m = resultSetToModule(rs)) != null) {
{
moduleList.add(m); moduleList.add(m);
} }
return moduleList.toArray(new Module[0]); return moduleList.toArray(new Module[0]);
} } catch (Exception ex) {
catch (Exception ex){
return null; return null;
} }
} }
public Module addModule(Module m) public Module addModule(Module m) {
{
try { try {
st.executeUpdate("insert into modules (userid, semesterid, name, activated) " + st.executeUpdate("insert into modules (userid, semesterid, name, activated) " +
"Values (" + m.getUserid() + ", " + m.getSemesterId() + ", '" + m.getName() + "', " + m.getActivated() + ")"); "Values (" + m.getUserid() + ", " + m.getsemesterid() + ", '" + m.getName() + "', " + m.getActivated() + ")");
return getModule(m.getUserid(), m.getSemesterId(), m.getName()); return getModule(m.getUserid(), m.getsemesterid());
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public Module[] getAllModules() { public Module[] getAllModules() {
try try {
{
ResultSet rs = st.executeQuery("SELECT * FROM modules"); ResultSet rs = st.executeQuery("SELECT * FROM modules");
List<Module> moduleList = new ArrayList<>(); List<Module> moduleList = new ArrayList<>();
Module m = null; Module m = null;
while((m = resultSetToModule(rs)) != null) while ((m = resultSetToModule(rs)) != null) {
{
moduleList.add(m); moduleList.add(m);
} }
return moduleList.toArray(new Module[0]); return moduleList.toArray(new Module[0]);
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
public Module updateModule(Module m) public Module updateModule(Module m) {
{
System.out.println(m.getActivated());
try { try {
st.executeUpdate("update modules set activated=" + m.getActivated() + " where userid=" + m.getUserid() + " and semesterid=" + m.getSemesterId() + " and name='" + m.getName() + "'");
return getModule(m.getUserid(), m.getSemesterId(), m.getName());
} st.executeUpdate("update modules set activated=" + m.getActivated() + ", semesterid=" + m.getsemesterid() + ", name='" + m.getName() + "' where id=" + m.getid());
catch (SQLException ex) {
return null;
} catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
return null; return null;
} }
} }
public boolean deleteModule(int id) public boolean deleteModule(int id) {
{
try { try {
st.executeUpdate("DELETE FROM modules WHERE id=" + id); st.executeUpdate("delete from modules where id=" + id);
return true; return true;
} } catch (Exception ex) {
catch(Exception ex) {
return false; return false;
} }
} }
@@ -457,90 +357,72 @@ public class DataBaseHandler
rs.getInt("semesterid"), rs.getInt("semesterid"),
rs.getString("name"), rs.getString("name"),
rs.getInt("activated")); rs.getInt("activated"));
} } catch (Exception ex) {
catch (Exception ex) {
return null; return null;
} }
} }
/** /**
USER * USER
*/ */
//Alle User, die nicht admin sind
//TODO: Nur nicht admins werden aktuell ausgegeben public User[] getAllUsers() {
public User[] getAllUsers() try {
{
try
{
ResultSet rs = st.executeQuery("select * from users where permission=0"); ResultSet rs = st.executeQuery("select * from users where permission=0");
User u = null; User u = null;
List<User> output = new ArrayList<>(); List<User> output = new ArrayList<>();
while((u = resultSetToUser(rs)) != null) while ((u = resultSetToUser(rs)) != null) {
{
u.clearOutPassword(); u.clearOutPassword();
output.add(u); output.add(u);
} }
return output.toArray(new User[0]); return output.toArray(new User[0]);
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
//get a user object by mail and password from the database //einen User
public User getUser(String mail, String password) public User getUser(String mail, String password) {
{
try try {
{
ResultSet rs = st.executeQuery("select * from users where mail = '" + mail + "' and password = '" + password + "'"); ResultSet rs = st.executeQuery("select * from users where mail = '" + mail + "' and password = '" + password + "'");
return resultSetToUser(rs); return resultSetToUser(rs);
} catch (Exception e) } catch (Exception e) {
{
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public User getUser(int id) public User getUser(int id) {
{ try {
try
{
ResultSet rs = st.executeQuery("select * from users where id=" + id); ResultSet rs = st.executeQuery("select * from users where id=" + id);
return resultSetToUser(rs); return resultSetToUser(rs);
} catch (Exception e) } catch (Exception e) {
{
return null; return null;
} }
} }
public User getUser(String mail) public User getUser(String mail) {
{ try {
try
{
ResultSet rs = st.executeQuery("select * from users where mail='" + mail + "'"); ResultSet rs = st.executeQuery("select * from users where mail='" + mail + "'");
User u = resultSetToUser(rs); User u = resultSetToUser(rs);
if(u != null) u.clearOutPassword(); if (u != null) u.clearOutPassword();
return u; return u;
} catch (SQLException e) } catch (SQLException e) {
{
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public User resultSetToUser(ResultSet rs) public User resultSetToUser(ResultSet rs) {
{ try {
try
{
rs.next(); rs.next();
return new User( return new User(
rs.getInt("id"), rs.getInt("id"),
@@ -550,27 +432,21 @@ public class DataBaseHandler
rs.getString("password"), rs.getString("password"),
rs.getInt("permission") rs.getInt("permission")
); );
} } catch (Exception e) {
catch(Exception e)
{
return null; return null;
} }
} }
//add a new user object to the database returns if process was successful //add a new user object to the database returns if process was successful
public User addUser(User user) public User addUser(User user) {
{
//check if mail and passwort (key user information) is given //check if mail and passwort (key user information) is given
if (user.getMail() == null || user.getPassword() == null) if (user.getMail() == null || user.getPassword() == null) {
{
return null; return null;
} }
try try {
{
String password = user.getPassword(); String password = user.getPassword();
if(encrypted) if (encrypted) {
{
RSA rsa = RSA.getInstance(); RSA rsa = RSA.getInstance();
byte[] psw = rsa.loadByteArray(password); byte[] psw = rsa.loadByteArray(password);
try { try {
@@ -581,20 +457,16 @@ public class DataBaseHandler
} }
st.executeUpdate("insert into users (firstname, lastname, mail, password, permission) values (" + "'" + user.getFirstName() + "', '" + user.getLastName() + "', '" + user.getMail() + "', '" + password + "', " + 0 + ")"); st.executeUpdate("insert into users (firstname, lastname, mail, password, permission) values (" + "'" + user.getFirstName() + "', '" + user.getLastName() + "', '" + user.getMail() + "', '" + password + "', " + 0 + ")");
return getUser(user.getMail(), user.getPassword()); return getUser(user.getMail(), user.getPassword());
} catch (Exception e) } catch (Exception e) {
{
return null; return null;
} }
} }
public User updateUser(User user, int id, boolean elevationRequestByAdmin) public User updateUser(User user, int id, boolean elevationRequestByAdmin) {
{ try {
try
{
String password = user.getPassword(); String password = user.getPassword();
if(encrypted) if (encrypted) {
{
RSA rsa = RSA.getInstance(); RSA rsa = RSA.getInstance();
byte[] psw = rsa.loadByteArray(password); byte[] psw = rsa.loadByteArray(password);
try { try {
@@ -604,17 +476,14 @@ public class DataBaseHandler
} }
} }
if(!elevationRequestByAdmin) if (!elevationRequestByAdmin) {
{
st.executeUpdate("update users set " + st.executeUpdate("update users set " +
"firstname='" + user.getFirstName() + "', " + "firstname='" + user.getFirstName() + "', " +
"lastname='" + user.getLastName() + "', " + "lastname='" + user.getLastName() + "', " +
"mail='" + user.getMail() + "', " + "mail='" + user.getMail() + "', " +
"password='" + password + "' " + "password='" + password + "' " +
"where id=" + id); "where id=" + id);
} } else {
else
{
st.executeUpdate("update users set " + st.executeUpdate("update users set " +
"firstname='" + user.getFirstName() + "', " + "firstname='" + user.getFirstName() + "', " +
"lastname='" + user.getLastName() + "', " + "lastname='" + user.getLastName() + "', " +
@@ -625,17 +494,14 @@ public class DataBaseHandler
} }
return getUser(id); return getUser(id);
} catch (SQLException e) } catch (SQLException e) {
{
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public boolean deleteUser(String mail) public boolean deleteUser(String mail) {
{ try {
try
{
ResultSet rs = st.executeQuery("SELECT id FROM user WHERE mail='" + mail + "'"); ResultSet rs = st.executeQuery("SELECT id FROM user WHERE mail='" + mail + "'");
rs.next(); rs.next();
int id = rs.getInt("id"); int id = rs.getInt("id");
@@ -643,9 +509,7 @@ public class DataBaseHandler
st.executeUpdate("delete from users where mail='" + mail + "'"); st.executeUpdate("delete from users where mail='" + mail + "'");
return true; return true;
} } catch (Exception e) {
catch(Exception e)
{
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@@ -4,22 +4,24 @@ package com.example.backend.anwprj.Entries;
public class Entry public class Entry
{ {
private int id; private int id;
private int dayid; private int daynumber;
private int yearnumber;
private int usercreatedbyid; private int usercreatedbyid;
private int timestart; private int timestart;
private int timeend; private int timeend;
private int semesterid;
private String info; private String info;
private int editable;
public Entry(int id, int dayid, int usercreatedbyid, int timestart, int timeend, String info, int editable) public Entry(int id, int daynumber, int yearnumber, int usercreatedbyid, int timestart, int timeend, int semesterid, String info)
{ {
this.id = id; this.id = id;
this.dayid = dayid; this.daynumber = daynumber;
this.yearnumber = yearnumber;
this.usercreatedbyid = usercreatedbyid; this.usercreatedbyid = usercreatedbyid;
this.timestart = timestart; this.timestart = timestart;
this.timeend = timeend; this.timeend = timeend;
this.semesterid = semesterid;
this.info = info; this.info = info;
this.editable = editable;
} }
public int getId() public int getId()
@@ -27,9 +29,14 @@ public class Entry
return id; return id;
} }
public int getDayid() public int getDaynumber()
{ {
return dayid; return daynumber;
}
public int getYearnumber()
{
return yearnumber;
} }
public int getUsercreatedbyid() public int getUsercreatedbyid()
@@ -47,33 +54,13 @@ public class Entry
return timeend; return timeend;
} }
public int getSemesterid()
{
return semesterid;
}
public String getInfo() public String getInfo()
{ {
return info; return info;
} }
public void setDayid(int dayid)
{
this.dayid = dayid;
}
public void setTimestart(int timestart)
{
this.timestart = timestart;
}
public void setTimeend(int timeend)
{
this.timeend = timeend;
}
public void setInfo(String info)
{
this.info = info;
}
public int getEditable()
{
return editable;
}
} }
@@ -18,11 +18,11 @@ public class Module {
this.activated = activated; this.activated = activated;
} }
public int getId() { return id; } public int getid() { return id; }
public int getUserid() { return userid; } public int getUserid() { return userid; }
public int getSemesterId() { return semesterid; } public int getsemesterid() { return semesterid; }
public String getName() { return name; } public String getName() { return name; }
@@ -9,14 +9,16 @@ public class Semester
private String name; private String name;
private int startyear; private int startyear;
private int endyear; private int endyear;
private int number;
public Semester(int id, int startday, int endday, String name, int startyear, int endyear) { public Semester(int id, int startday, int endday, String name, int startyear, int endyear, int number) {
this.id = id; this.id = id;
this.startday = startday; this.startday = startday;
this.endday = endday; this.endday = endday;
this.name = name; this.name = name;
this.startyear = startyear; this.startyear = startyear;
this.endyear = endyear; this.endyear = endyear;
this.number = number;
} }
public int getId() { public int getId() {
@@ -42,4 +44,6 @@ public class Semester
public int getEndyear() { public int getEndyear() {
return endyear; return endyear;
} }
public int getNumber(){return number; }
} }
@@ -1,6 +1,6 @@
package com.example.backend.anwprj.Users; package com.example.backend.anwprj.Users;
import com.example.backend.anwprj.DataBaseHandler; import com.example.backend.anwprj.Database.DataBaseHandler;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
@@ -1,60 +0,0 @@
package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.DataBaseHandler;
import com.example.backend.anwprj.Days.Day;
import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class DayController
{
private DataBaseHandler db;
{
db = DataBaseHandler.getInstance();
}
@CrossOrigin
@GetMapping("/days")
public ResponseEntity<Day> getDay(
@RequestParam(name="sessionid") String sessionID,
@RequestParam(name="dayinyear") int dayinyear,
@RequestParam(name="yearnumber") int yearnumber,
@RequestParam(name="semesterid") int semesterID)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u != null)
{
Day d = db.getDay(dayinyear, yearnumber, semesterID);
if (d != null)
{
return new ResponseEntity<>(d, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@CrossOrigin
@PostMapping("/days")
public ResponseEntity<Day> addDay(@RequestBody Day day, @RequestParam(name="sessionid") String sessionID)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue())
{
return new ResponseEntity<>(db.addDay(day), HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
}
}
@@ -1,8 +1,9 @@
package com.example.backend.anwprj.controller; package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.DataBaseHandler; import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.anwprj.Entries.Entry; import com.example.backend.anwprj.Entries.Entry;
import com.example.backend.anwprj.Users.User; import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler; import com.example.backend.anwprj.Users.UserSessionIDHandler;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -17,29 +18,122 @@ public class EntriesController
db = DataBaseHandler.getInstance(); db = DataBaseHandler.getInstance();
} }
/**
GET
a set of entries for a week, based on the semester, the startdaynumber of the week and the year
Every user is allowed
*/
@CrossOrigin @CrossOrigin
@GetMapping("/entries") @GetMapping("/entries")
public ResponseEntity<Entry[]> getEntries( public ResponseEntity<Entry[][]> getEntries(@RequestParam(name = "semesterid") int semesterid,
@RequestParam(name = "sessionid") String sessionID, @RequestParam(name = "daynumber") int daynumber,
@RequestParam(name = "dayinweek") int dayinweek, @RequestParam(name = "yearnumber") int yearnumber,
@RequestParam(name = "weeknumber") int weeknumber, @RequestParam(name = "sessionid") String sessionid)
@RequestParam(name = "semesterid") int semesterid)
{ {
User user = UserSessionIDHandler.getUserBySessionID(sessionID); User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionid);
if(user == null) if (sessionUser != null)
{ {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); var lonelyEntry = db.getEntries(semesterid, daynumber, yearnumber);
var happyEntry = db.getAllEntrys(semesterid, daynumber, yearnumber, sessionUser.getId());
var combinedEntry = new Entry[6][20];
for (int i = 0; i < 6; i++) {
var idx = 0;
for (int j = 0; j < 20; j++) {
if (lonelyEntry != null && lonelyEntry[i][j] != null){
combinedEntry[i][idx] = lonelyEntry[i][j];
idx++;
}
if (happyEntry != null && happyEntry[i][j] != null){
combinedEntry[i][idx] = happyEntry[i][j];
idx++;
}
}
} }
Entry[] entries = db.getEntries(dayinweek, weeknumber, semesterid, user);
return new ResponseEntity<>(entries, HttpStatus.OK); return new ResponseEntity<>(combinedEntry, HttpStatus.OK);
} }
return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
}
@CrossOrigin
@GetMapping("/entries/planned")
public ResponseEntity<Integer[]> getEntries(@RequestParam(name = "semesterid") int semesterid,
@RequestParam(name = "sessionid") String sessionid)
{
User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionid);
if (sessionUser != null)
{
var entries = db.getAllEntries(semesterid, sessionUser.getId());
var count = 0;
for (int i = 0; i < entries.length; i++) {
count += entries[i].getTimeend()-entries[i].getTimestart();
}
return new ResponseEntity<>(new Integer[]{count}, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
/**
POST
A new entry to the database. Every user except of admins is allowed
*/
@CrossOrigin @CrossOrigin
@PostMapping("/entries") @PostMapping("/entries")
public ResponseEntity<Entry[]> postEntries(@RequestBody Entry[] entries, @RequestParam(name="sessionid") String sessionID) public ResponseEntity<Boolean> postEntry(@RequestBody Entry entry, @RequestParam(name = "sessionid") String sessionid)
{ {
return null; User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionid);
if (sessionUser != null && sessionUser.getPermissions() == UserPermissions.self.getValue())
{
db.addEntry(entry);
return new ResponseEntity<>(true, HttpStatus.OK);
} }
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
}
/**
PUT
Update the endTime of an existing entry in the database. Every user except of admins is allowed
*/
@CrossOrigin
@PutMapping("/entries")
public ResponseEntity<Boolean> updateEntry(@RequestParam(name="sessionid") String sessionid, @RequestBody Entry entry)
{
User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionid);
if (sessionUser != null)
{
db.updateEntry(entry);
return new ResponseEntity<>(true, HttpStatus.OK);
}
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
}
/**
Delete
an existing entry from the database
*/
@CrossOrigin
@DeleteMapping("/entries")
public ResponseEntity<Boolean> deleteEntry(@RequestParam(name = "id") int id, @RequestParam(name = "sessionid") String sessionid)
{
User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionid);
if (sessionUser != null)
{
db.deleteEntry(id);
return new ResponseEntity<>(true, HttpStatus.OK);
}
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
}
} }
@@ -1,6 +1,6 @@
package com.example.backend.anwprj.controller; package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.DataBaseHandler; import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.anwprj.Module.Module; import com.example.backend.anwprj.Module.Module;
import com.example.backend.anwprj.Users.User; import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions; import com.example.backend.anwprj.Users.UserPermissions;
@@ -9,45 +9,41 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Ein Modul hier entspricht nicht z.b. Analysis im Allgemeinen.
* Es beschreibt die Verbindung zwischen einem Dozenten und Analysis in einem Speziellen Semester.
*/
@RestController @RestController
public class ModuleController { public class ModuleController
{
private final DataBaseHandler db; private final DataBaseHandler db;
{ {
db = DataBaseHandler.getInstance(); db = DataBaseHandler.getInstance();
} }
// @CrossOrigin
// @GetMapping("/module")
// public ResponseEntity<Module> getModule(
// @RequestParam(name="id") int id,
// @RequestParam(name="sessionid") String sessionID) {
//
// User user = UserSessionIDHandler.getUserBySessionID(sessionID);
//
// if (user != null){
// Module module = db.getModule(id);
// if(module != null) {
// return new ResponseEntity<>(module, HttpStatus.OK);
// }
//
// return new ResponseEntity<>(HttpStatus.NOT_FOUND);
// }
//
// return new ResponseEntity<>(HttpStatus.FORBIDDEN);
// }
/**
GET
A Module by its id
*/
@CrossOrigin @CrossOrigin
@GetMapping("/module/id") @GetMapping("/module/id")
public ResponseEntity<Module[]> getModules( public ResponseEntity<Module[]> getModules(
@RequestParam(name="sessionid") String sessionID) { @RequestParam(name = "sessionid") String sessionID)
{
User user = UserSessionIDHandler.getUserBySessionID(sessionID); User user = UserSessionIDHandler.getUserBySessionID(sessionID);
if(user != null) if (user != null)
{ {
Module[] modules = db.getModules(user.getId()); Module[] modules = db.getModules(user.getId());
if (modules != null) { if (modules != null)
{
return new ResponseEntity<>(modules, HttpStatus.OK); return new ResponseEntity<>(modules, HttpStatus.OK);
} }
@@ -57,13 +53,45 @@ public class ModuleController {
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
@CrossOrigin
@GetMapping("/module/bysemesterid")
public ResponseEntity<Module[]> getModulesBySemesterID(@RequestParam(name="sessionid") String sessionID, @RequestParam(name="semesterid") int semesterid)
{
User user = UserSessionIDHandler.getUserBySessionID(sessionID);
if(user != null && user.getPermissions() == UserPermissions.admin.getValue())
{
Module[] tempModuleArray = db.getAllModules();
List<Module> result = new ArrayList<>();
for(int i = 0; i < tempModuleArray.length; i++)
{
if(tempModuleArray[i].getsemesterid() == semesterid)
{
result.add(tempModuleArray[i]);
}
}
return new ResponseEntity<>(result.toArray(new Module[0]), HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
/**
GET
all modules from the database. (Not used now)
*/
@CrossOrigin @CrossOrigin
@GetMapping("/module/all") @GetMapping("/module/all")
public ResponseEntity<Module[]> getModule(@RequestParam(name="sessionid") String sessionid) { public ResponseEntity<Module[]> getModule(@RequestParam(name = "sessionid") String sessionid)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionid); User u = UserSessionIDHandler.getUserBySessionID(sessionid);
if(u != null) { if (u != null)
if(u.getPermissions() == UserPermissions.admin.getValue()) { {
if (u.getPermissions() == UserPermissions.admin.getValue())
{
return new ResponseEntity<>(db.getAllModules(), HttpStatus.OK); return new ResponseEntity<>(db.getAllModules(), HttpStatus.OK);
} }
} }
@@ -71,14 +99,22 @@ public class ModuleController {
return null; return null;
} }
/**
POST
a new module entry. (When a user is selected in a semester.)
*/
@CrossOrigin @CrossOrigin
@PostMapping("/module") @PostMapping("/module")
public ResponseEntity<Module> addModule(@RequestBody Module module, @RequestParam(name="sessionid") String sessionID) { public ResponseEntity<Module> addModule(@RequestBody Module module, @RequestParam(name = "sessionid") String sessionID)
{
User user = UserSessionIDHandler.getUserBySessionID(sessionID); User user = UserSessionIDHandler.getUserBySessionID(sessionID);
if(user.getPermissions() == UserPermissions.admin.getValue()) { if (user.getPermissions() == UserPermissions.admin.getValue())
{
Module m = db.addModule(module); Module m = db.addModule(module);
if(m != null) { if (m != null)
{
return new ResponseEntity<>(m, HttpStatus.OK); return new ResponseEntity<>(m, HttpStatus.OK);
} }
@@ -89,14 +125,22 @@ public class ModuleController {
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
/**
PUT
Update a Module
*/
@CrossOrigin @CrossOrigin
@PutMapping("/module") @PutMapping("/module")
public ResponseEntity<Module> updateModule(@RequestBody Module module, @RequestParam(name="sessionid") String sessionID) { public ResponseEntity<Module> updateModule(@RequestBody Module module, @RequestParam(name = "sessionid") String sessionID)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionID); User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue()) { if (u != null)
{
Module m = db.updateModule(module); Module m = db.updateModule(module);
if(m != null) { if (m != null)
{
return new ResponseEntity<>(m, HttpStatus.OK); return new ResponseEntity<>(m, HttpStatus.OK);
} }
@@ -106,11 +150,17 @@ public class ModuleController {
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
/**
DELETE
Delete A Module
*/
@CrossOrigin @CrossOrigin
@DeleteMapping("/module") @DeleteMapping("/module")
public void deleteModule(@RequestParam(name="sessionid") String sessionid, @RequestParam(name="id") int id) { public void deleteModule(@RequestParam(name = "sessionid") String sessionid, @RequestParam(name="id") int id)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionid); User u = UserSessionIDHandler.getUserBySessionID(sessionid);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue()) { if (u != null && u.getPermissions() == UserPermissions.admin.getValue())
{
db.deleteModule(id); db.deleteModule(id);
} }
@@ -1,6 +1,6 @@
package com.example.backend.anwprj.controller; package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.DataBaseHandler; import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.anwprj.Semesters.Semester; import com.example.backend.anwprj.Semesters.Semester;
import com.example.backend.anwprj.Users.User; import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions; import com.example.backend.anwprj.Users.UserPermissions;
@@ -9,7 +9,8 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Arrays; import java.util.ArrayList;
import java.util.List;
@RestController @RestController
public class SemesterController public class SemesterController
@@ -21,29 +22,6 @@ public class SemesterController
db = DataBaseHandler.getInstance(); db = DataBaseHandler.getInstance();
} }
//a new semester add is requested (only allowed for admin users)
@CrossOrigin
@PostMapping("/semester")
public ResponseEntity<Semester> addSemester(@RequestBody Semester semester, @RequestParam(name="sessionid") String sessionID)
{
User user = UserSessionIDHandler.getUserBySessionID(sessionID);
if(user.getPermissions() == UserPermissions.admin.getValue())
{
Semester s = db.addSemester(semester);
if(s != null)
{
System.out.println(s.getStartday());
return new ResponseEntity<>(s, HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
//get a semester object by its name //get a semester object by its name
@CrossOrigin @CrossOrigin
@GetMapping("/semester") @GetMapping("/semester")
@@ -79,12 +57,29 @@ public class SemesterController
return new ResponseEntity<>(s, HttpStatus.OK); return new ResponseEntity<>(s, HttpStatus.OK);
} }
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(null, HttpStatus.OK);
} }
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
@CrossOrigin
@GetMapping("/semester/id/all")
public ResponseEntity<Semester[]> getSemestersAll(@RequestParam(name="ids") String ids, @RequestParam(name="sessionid") String sessionid)
{
String[] idsSplit = ids.split("a");
List<Semester> resultList = new ArrayList<>();
for(int i = 0; i < idsSplit.length; i++)
{
int currentID = Integer.parseInt(idsSplit[i]);
resultList.add(db.getSemester(currentID));
}
return new ResponseEntity<>(resultList.toArray(new Semester[0]), HttpStatus.OK);
}
@CrossOrigin @CrossOrigin
@GetMapping("/semester/all") @GetMapping("/semester/all")
public ResponseEntity<Semester[]> getSemester(@RequestParam(name="sessionid") String sessionid) public ResponseEntity<Semester[]> getSemester(@RequestParam(name="sessionid") String sessionid)
@@ -102,6 +97,31 @@ public class SemesterController
return null; return null;
} }
//a new semester add is requested (only allowed for admin users)
@CrossOrigin
@PostMapping("/semester")
public ResponseEntity<Semester> addSemester(@RequestBody Semester semester, @RequestParam(name="sessionid") String sessionID)
{
User user = UserSessionIDHandler.getUserBySessionID(sessionID);
if(user.getPermissions() == UserPermissions.admin.getValue())
{
Semester s = db.addSemester(semester);
if(s != null)
{
return new ResponseEntity<>(s, HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@CrossOrigin @CrossOrigin
@PutMapping("/semester") @PutMapping("/semester")
public ResponseEntity<Semester> updateSemester(@RequestBody Semester semester, @RequestParam(name="sessionid") String sessionID) public ResponseEntity<Semester> updateSemester(@RequestBody Semester semester, @RequestParam(name="sessionid") String sessionID)
@@ -109,7 +129,6 @@ public class SemesterController
User u = UserSessionIDHandler.getUserBySessionID(sessionID); User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue()) if(u != null && u.getPermissions() == UserPermissions.admin.getValue())
{ {
System.out.println(semester.getId());
Semester s = db.updateSemester(semester); Semester s = db.updateSemester(semester);
if(s != null) if(s != null)
@@ -1,7 +1,7 @@
package com.example.backend.anwprj.controller; package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.Encryption.RSA; import com.example.backend.discard.Encryption.RSA;
import com.example.backend.anwprj.DataBaseHandler; import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.anwprj.Users.User; import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions; import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler; import com.example.backend.anwprj.Users.UserSessionIDHandler;
@@ -18,6 +18,84 @@ public class UserController {
db = DataBaseHandler.getInstance(); db = DataBaseHandler.getInstance();
} }
@CrossOrigin
@GetMapping("/users/all")
public ResponseEntity<User[]> getAllUsers(@RequestParam(name = "sessionid") String sessionid)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionid);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue())
{
User[] output = db.getAllUsers();
return new ResponseEntity<>(output, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
//a user wants to login
@CrossOrigin
@GetMapping("/users")
public ResponseEntity<String> login(@RequestParam(name = "mail") String mail, @RequestParam(name = "password") String password) {
//generate a session id for the user trying to login
boolean isEncrypted = false;
if(isEncrypted)
{
RSA rsa = RSA.getInstance();
byte[] psw = rsa.loadByteArray(password);
try {
password = rsa.decrypt(psw);
} catch (Exception e) {
e.printStackTrace();
}
}
mail = mail.toLowerCase();
String sessionID = UserSessionIDHandler.addUser(mail, password);
return new ResponseEntity<>(sessionID, HttpStatus.OK);
}
@CrossOrigin
@GetMapping("/users/logout")
public ResponseEntity<Boolean> logout(@RequestParam(name = "sessionid") String sessionID) {
boolean success = UserSessionIDHandler.removeUser(sessionID);
return new ResponseEntity<>(success, HttpStatus.OK);
}
@CrossOrigin
@GetMapping("/users/data")
public ResponseEntity<User> getUserData(
@RequestParam(name = "sessionid") String sessionID,
@RequestParam(name = "mail") String mail) {
User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionID);
if (sessionUser != null) {
System.out.println(sessionUser.getMail() + " " + mail);
if (sessionUser.getMail().equals(mail) || sessionUser.getPermissions() == UserPermissions.admin.getValue()) {
User searchedUser = db.getUser(mail);
return new ResponseEntity<>(searchedUser, HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@CrossOrigin
@GetMapping("/users/check")
public ResponseEntity<User> checkLogin(@RequestParam(name="sessionid") String sessionid)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionid);
if(u != null)
{
return new ResponseEntity<>(db.getUser(u.getId()), HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
//adds a new user to the database (cannot create an admin user) //adds a new user to the database (cannot create an admin user)
@CrossOrigin @CrossOrigin
@@ -40,35 +118,6 @@ public class UserController {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
} }
//a user wants to login
@CrossOrigin
@GetMapping("/users")
public ResponseEntity<String> login(@RequestParam(name = "mail") String mail, @RequestParam(name = "password") String password) {
//generate a session id for the user trying to login
boolean isEncrypted = false;
if(isEncrypted)
{
RSA rsa = RSA.getInstance();
byte[] psw = rsa.loadByteArray(password);
try {
password = rsa.decrypt(psw);
} catch (Exception e) {
e.printStackTrace();
}
}
String sessionID = UserSessionIDHandler.addUser(mail, password);
return new ResponseEntity<>(sessionID, HttpStatus.OK);
}
@CrossOrigin
@GetMapping("/users/logout")
public ResponseEntity<Boolean> logout(@RequestParam(name = "sessionid") String sessionID) {
boolean success = UserSessionIDHandler.removeUser(sessionID);
return new ResponseEntity<>(success, HttpStatus.OK);
}
@CrossOrigin @CrossOrigin
@PutMapping("/users") @PutMapping("/users")
public ResponseEntity<Boolean> updateUser(@RequestParam(name = "sessionid") String sessionID, @RequestBody User u, @RequestParam(name = "mail") String mail) { public ResponseEntity<Boolean> updateUser(@RequestParam(name = "sessionid") String sessionID, @RequestBody User u, @RequestParam(name = "mail") String mail) {
@@ -121,25 +170,6 @@ public class UserController {
return new ResponseEntity<>(false, HttpStatus.FORBIDDEN); return new ResponseEntity<>(false, HttpStatus.FORBIDDEN);
} }
@CrossOrigin
@GetMapping("/users/data")
public ResponseEntity<User> getUserData(
@RequestParam(name = "sessionid") String sessionID,
@RequestParam(name = "mail") String mail) {
User sessionUser = UserSessionIDHandler.getUserBySessionID(sessionID);
if (sessionUser != null) {
System.out.println(sessionUser.getMail() + " " + mail);
if (sessionUser.getMail().equals(mail) || sessionUser.getPermissions() == UserPermissions.admin.getValue()) {
User searchedUser = db.getUser(mail);
return new ResponseEntity<>(searchedUser, HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@CrossOrigin @CrossOrigin
@DeleteMapping("/users") @DeleteMapping("/users")
public ResponseEntity<Boolean> deleteUser(@RequestParam(name = "sessionid") String sessionID, @RequestParam(name = "mail") String mail) { public ResponseEntity<Boolean> deleteUser(@RequestParam(name = "sessionid") String sessionID, @RequestParam(name = "mail") String mail) {
@@ -152,18 +182,4 @@ public class UserController {
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
@CrossOrigin
@GetMapping("/users/all")
public ResponseEntity<User[]> getAllUsers(@RequestParam(name = "sessionid") String sessionid)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionid);
if(u != null && u.getPermissions() == UserPermissions.admin.getValue())
{
User[] output = db.getAllUsers();
return new ResponseEntity<>(output, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
} }
@@ -1,60 +0,0 @@
package com.example.backend.anwprj.controller;
import com.example.backend.anwprj.DataBaseHandler;
import com.example.backend.anwprj.Days.Day;
import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler;
import org.springframework.http.HttpStatus;
import com.example.backend.anwprj.Week.Week;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
@RestController
public class WeekController
{
private DataBaseHandler db;
{
db = DataBaseHandler.getInstance();
}
@CrossOrigin
@GetMapping("/weeks")
public ResponseEntity<Week> getWeek(
@RequestParam(name="sessionid") String sessionID,
@RequestParam(name="semesterid") int semesterID,
@RequestParam(name="weeknumber") int weekNumber) throws SQLException {
User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u != null)
{
Week w = db.getWeek(semesterID,weekNumber);
if(w != null)
{
return new ResponseEntity<>(w, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@CrossOrigin
@PostMapping("/weeks")
public ResponseEntity<Week> addWeek(@RequestBody Week week, @RequestParam(name="sessionid") String sessionID)
{
User u = UserSessionIDHandler.getUserBySessionID(sessionID);
if(u !=null && u.getPermissions() == UserPermissions.admin.getValue())
{
return new ResponseEntity<>(db.addWeek(week), HttpStatus.OK);
}
return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
}
}
@@ -0,0 +1,60 @@
package com.example.backend.discard;
import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.discard.Days.Day;
import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class DayController
{
// private DataBaseHandler db;
//
// {
// db = DataBaseHandler.getInstance();
// }
//
// @CrossOrigin
// @GetMapping("/days")
// public ResponseEntity<Day> getDay(
// @RequestParam(name="sessionid") String sessionID,
// @RequestParam(name="dayinyear") int dayinyear,
// @RequestParam(name="yearnumber") int yearnumber,
// @RequestParam(name="semesterid") int semesterID)
// {
// User u = UserSessionIDHandler.getUserBySessionID(sessionID);
//
// if(u != null)
// {
// Day d = db.getDay(dayinyear, yearnumber, semesterID);
//
// if (d != null)
// {
// return new ResponseEntity<>(d, HttpStatus.OK);
// }
//
// return new ResponseEntity<>(HttpStatus.NOT_FOUND);
// }
//
// return new ResponseEntity<>(HttpStatus.FORBIDDEN);
// }
//
// @CrossOrigin
// @PostMapping("/days")
// public ResponseEntity<Day> addDay(@RequestBody Day day, @RequestParam(name="sessionid") String sessionID)
// {
// User u = UserSessionIDHandler.getUserBySessionID(sessionID);
//
// if(u != null && u.getPermissions() == UserPermissions.admin.getValue())
// {
// return new ResponseEntity<>(db.addDay(day), HttpStatus.OK);
// }
//
// return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
// }
}
@@ -1,4 +1,4 @@
package com.example.backend.anwprj.Days; package com.example.backend.discard.Days;
public class Day public class Day
{ {
@@ -1,4 +1,4 @@
package com.example.backend.anwprj.Encryption; package com.example.backend.discard.Encryption;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import java.io.*; import java.io.*;
@@ -0,0 +1,124 @@
/**
* WEEKS
*/
public Week addWeek(Week week)
{
try
{
st.executeUpdate("insert into weeks (semesterid, weeknumber) values (" + week.getSemesterid() + ", " + week.getWeeknumber() + ")");
return getWeek(week.getSemesterid(), week.getWeeknumber());
} catch (SQLException e)
{
return null;
}
}
public Week getWeek(int id)
{
ResultSet rs = null;
try
{
rs = st.executeQuery("select * from weeks where id=" + id);
return resultSetToWeek(rs);
} catch (SQLException e)
{
return null;
}
}
public Week getWeek(int semesterid, int weeknumber)
{
try
{
ResultSet rs = st.executeQuery("select * from weeks where semesterid =" + semesterid + " and weeknumber=" + weeknumber);
return resultSetToWeek(rs);
}
catch (SQLException e)
{
return null;
}
}
private Week resultSetToWeek(ResultSet rs) {
try {
rs.next();
return new Week(
rs.getInt("id"),
rs.getInt("semesterid"),
rs.getInt("weeknumber")
);
} catch (SQLException e) {
return null;
}
}
/**
DAYS
*/
public Day addDay(Day day)
{
try
{
st.executeUpdate("insert into days (dayinyear, yearnumber, semesterid) values (" + day.getDayinyear() + ", " + day.getYearnumber() + ", " + day.getSemesterid() + ")");
return getDay(day.getDayinyear(), day.getYearnumber(), day.getSemesterid());
} catch (SQLException e)
{
return null;
}
}
public Day getDay(int id)
{
try
{
ResultSet rs = st.executeQuery("select * from days where id=" + id);
return resultSetToDay(rs);
}
catch(Exception e)
{
return null;
}
}
public Day getDay(int dayinyear, int yearnumber, int semesterid)
{
try
{
ResultSet rs = st.executeQuery("select * from days where dayinyear =" + dayinyear + " and yearnumber =" + yearnumber + " and semesterid =" + semesterid);
return resultSetToDay(rs);
}
catch(Exception e)
{
return null;
}
}
private Day resultSetToDay(ResultSet rs)
{
try
{
rs.next();
return new Day(
rs.getInt("id"),
rs.getInt("dayinyear"),
rs.getInt("yearnumber"),
rs.getInt("semesterid")
);
} catch (SQLException e)
{
return null;
}
}
@@ -1,4 +1,4 @@
package com.example.backend.anwprj.Week; package com.example.backend.discard.Week;
public class Week { public class Week {
@@ -0,0 +1,59 @@
package com.example.backend.discard;
import com.example.backend.anwprj.Database.DataBaseHandler;
import com.example.backend.anwprj.Users.User;
import com.example.backend.anwprj.Users.UserPermissions;
import com.example.backend.anwprj.Users.UserSessionIDHandler;
import org.springframework.http.HttpStatus;
import com.example.backend.discard.Week.Week;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
@RestController
public class WeekController
{
// private DataBaseHandler db;
//
// {
// db = DataBaseHandler.getInstance();
// }
//
// @CrossOrigin
// @GetMapping("/weeks")
// public ResponseEntity<Week> getWeek(
// @RequestParam(name="sessionid") String sessionID,
// @RequestParam(name="semesterid") int semesterID,
// @RequestParam(name="weeknumber") int weekNumber) throws SQLException {
// User u = UserSessionIDHandler.getUserBySessionID(sessionID);
//
// if(u != null)
// {
// Week w = db.getWeek(semesterID,weekNumber);
//
// if(w != null)
// {
// return new ResponseEntity<>(w, HttpStatus.OK);
// }
// return new ResponseEntity<>(HttpStatus.NOT_FOUND);
// }
// return new ResponseEntity<>(HttpStatus.FORBIDDEN);
// }
//
// @CrossOrigin
// @PostMapping("/weeks")
// public ResponseEntity<Week> addWeek(@RequestBody Week week, @RequestParam(name="sessionid") String sessionID)
// {
// User u = UserSessionIDHandler.getUserBySessionID(sessionID);
//
// if(u !=null && u.getPermissions() == UserPermissions.admin.getValue())
// {
// return new ResponseEntity<>(db.addWeek(week), HttpStatus.OK);
// }
//
// return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
// }
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "TIF22A_AnwProjekt_B",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/feiertagejs": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/feiertagejs/-/feiertagejs-1.3.9.tgz",
"integrity": "sha512-tUP+WBv2OWBhPwe3NfqwCtjMq+ym598a42tfqmL0FySswEb9xs96p2iKwqqx+lxKieu1njJBRZKsFm92bJhxZw==",
"engines": {
"node": ">=8.0.0"
}
}
}
}
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Simon Fakir
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
# Feiertage.js
[![npm version](https://badge.fury.io/js/feiertagejs.svg)](https://badge.fury.io/js/feiertagejs)
[![Build Status](https://travis-ci.org/sfakir/feiertagejs.svg?branch=master)](https://travis-ci.org/sfakir/feiertagejs)
Feiertage.js is a small *typescript* npm module without dependencies to calculate German holidays for each Bundesland.
## Installation
- [yarn](https://yarnpkg.com/en/): `yarn add feiertagejs`
- [npm](https://www.npmjs.com/): `npm install feiertagejs`
- [bower](https://bower.io/): `bower install feiertagejs` *outdated!*
- [Plain Javascript](http://extern.fakir.it/feiertagejs/feiertagejs.zip) *outdated!*
## Quick Examples
### ES Modules (Typescript/Javasript)
The prefered whay is to directly import the typescript module. However, you can also use .js.
Please find here some examples and full api [here](docs.md).
```javascript
import { getHolidays, isHoliday, isSpecificHoliday } from 'feiertagejs';
const today = new Date();
console.log(isHoliday(today, 'BW'));
// probably false, because you are working ;)
// check if a day is a specific holiday:
console.log(isSpecificHoliday(today, 'CHRISTIHIMMELFAHRT','ALL'));
// get all holiday for a single year: getHolidays()
// returns an array of "Holiday" Objects. Please see the docs.md for all properties.
const holidays2023 = getHolidays('2023','BUND');
console.log('date', holidays2023[0].date); // = Date("2023-01-01");
console.log('name', holidays2023[0].name); // 'NEUJAHRSTAG' (constant)
console.log('translation', holidays2023[0].trans('de')); // German translation: Neujahrstag
console.log('equals?', holidays2023[0].equals(date)); // Compare days only (ignore time)
```
### Usage in Node.js
```javascript
var feiertagejs = require('feiertagejs');
var today = new Date();
console.log(feiertagejs.isHoliday(today, 'BW'));
// probably false, because you are working ;)
// check if a day is a specific holiday:
console.log(feiertagejs.isSpecificHoliday(today, 'CHRISTIHIMMELFAHRT'));
// get all holiday for a single year: getHolidays()
// returns an array of "Holiday" Objects. Please see the docs.md for all properties.
var holidays2023 = feiertagejs.getHolidays('2023', 'BUND');
console.log('date', holidays2023[0].date); // = Date("2023-01-01");
console.log('name', holidays2023[0].name); // 'NEUJAHRSTAG' (constant)
console.log('translation', holidays2023[0].translate()); // German translation: Neujahrstag
console.log('equals?', holidays2023[0].equals(date)); // Compare days only (ignore time)
```
## API doc
The full API doc can be found [here](docs.md).
## Feedback and Questions
You have two options two give feedback or ask questions:
* Comment the official release [post](https://fakir.tech/de/feiertage-js-deutsche-feiertage-fuer-node-js-und-browser-javascript/)
* Open issues or pullrequests on [github](https://github.com/sfakir/feiertagejs)
## Contributors
Thank you for contributing:
* thetric
* SteveOswald
## Feedback
If you have any questions, feel free to open an issue.
+476
View File
@@ -0,0 +1,476 @@
const germanTranslations = {
NEUJAHRSTAG: 'Neujahrstag',
HEILIGEDREIKOENIGE: 'Heilige Drei Könige',
KARFREITAG: 'Karfreitag',
OSTERSONNTAG: 'Ostersonntag',
OSTERMONTAG: 'Ostermontag',
TAG_DER_ARBEIT: 'Tag der Arbeit',
CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',
PFINGSTSONNTAG: 'Pfingstsonntag',
PFINGSTMONTAG: 'Pfingstmontag',
FRONLEICHNAM: 'Fronleichnam',
MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',
DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',
REFORMATIONSTAG: 'Reformationstag',
ALLERHEILIGEN: 'Allerheiligen',
BUBETAG: 'Buß- und Bettag',
ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',
ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',
WELTKINDERTAG: 'Weltkindertag',
WELTFRAUENTAG: 'Weltfrauentag',
AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',
};
const allHolidays = [
'NEUJAHRSTAG',
'HEILIGEDREIKOENIGE',
'KARFREITAG',
'OSTERSONNTAG',
'OSTERMONTAG',
'TAG_DER_ARBEIT',
'CHRISTIHIMMELFAHRT',
'MARIAHIMMELFAHRT',
'PFINGSTSONNTAG',
'PFINGSTMONTAG',
'FRONLEICHNAM',
'DEUTSCHEEINHEIT',
'REFORMATIONSTAG',
'ALLERHEILIGEN',
'BUBETAG',
'ERSTERWEIHNACHTSFEIERTAG',
'ZWEITERWEIHNACHTSFEIERTAG',
'WELTKINDERTAG',
'WELTFRAUENTAG',
'AUGSBURGER_FRIEDENSFEST',
];
const allRegions = [
'BW',
'BY',
'BE',
'BB',
'HB',
'HE',
'HH',
'MV',
'NI',
'NW',
'RP',
'SL',
'SN',
'ST',
'SH',
'TH',
'BUND',
'AUGSBURG',
'ALL',
];
/*!
* feiertage.js
* @repository https://github.com/sfakir/feiertagejs
* @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md
*
* Copyright 2015-2021 Simon Fakir
* Released under the MIT license
*/
// translations
const defaultLanguage = 'de';
let currentLanguage = defaultLanguage;
const translations = {
de: germanTranslations,
};
/**
* adds a translation for the holidays (e.g. english).
* This also allows to override the German names.
* Hint: Interpolates German for missing translations
* @param {string} isoCode of the new language
* @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg
*/
function addTranslation(isoCode, newTranslation) {
const code = isoCode.toLowerCase();
const defaultTranslation = translations[defaultLanguage];
let missingFields = false;
// fill new Translation with default Language
for (const holiday of allHolidays) {
if (!newTranslation[holiday]) {
missingFields = true;
newTranslation[holiday] = defaultTranslation[holiday];
}
}
if (missingFields) {
console.warn('[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback');
}
translations[code] = newTranslation;
}
/**
* Set a language to default language
* @param {string} isoCode
*/
function setLanguage(isoCode) {
const code = isoCode.toLowerCase();
if (!translations[code]) {
throw new TypeError(`[feiertagejs] tried to set language to ${code} but the translation is missing. Please use addTranslation(isoCode,object) first`);
}
currentLanguage = isoCode;
}
/**
* Get currently set language
* @returns {string}
*/
function getLanguage() {
return currentLanguage;
}
// holidays api
/**
* Checks if a specific date is sunday or holiday.
* @param date
* @param region
* @returns {boolean}
*/
function isSunOrHoliday(date, region) {
checkRegion(region);
return date.getDay() === 0 || isHoliday(date, region);
}
/**
* Check is specific date is holiday.
* @param date
* @param {Region} region two character {@link Region} code
* @returns {boolean}
*/
function isHoliday(date, region) {
checkRegion(region);
const year = date.getFullYear();
const internalDate = toUtcTimestamp(date);
const holidays = getHolidaysAsUtcTimestamps(year, region);
return holidays.indexOf(internalDate) !== -1;
}
function getHolidayByDate(date, region = 'ALL') {
checkRegion(region);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
return holidays.find((holiday) => holiday.equals(date));
}
// additional runtime checks
/**
* Checks if the given region is a valid {@link Region}.
*
* @param region {@link Region} to check
* @throws {Error}
* @private
*/
function checkRegion(region) {
if (region === null || region === undefined) {
throw new Error(`Region must not be undefined or null`);
}
if (allRegions.indexOf(region) === -1) {
throw new Error(`Invalid region: ${region}! Must be one of ${allRegions.toString()}`);
}
}
/**
* Checks if the given holidayName is a valid {@link HolidayType}.
* @param holidayName {@link HolidayType} to check
* @throws {Error}
* @private
*/
function checkHolidayType(holidayName) {
if (holidayName === null || holidayName === undefined) {
throw new TypeError('holidayName must not be null or undefined');
}
if (allHolidays.indexOf(holidayName) === -1) {
throw new Error(`feiertage.js: invalid holiday type "${holidayName}"! Must be one of ${allHolidays.toString()}`);
}
}
function isSpecificHoliday(date, holidayName, region = 'ALL') {
checkRegion(region);
checkHolidayType(holidayName);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
const foundHoliday = holidays.find((holiday) => holiday.equals(date));
if (!foundHoliday) {
return false;
}
return foundHoliday.name === holidayName;
}
/**
* Returns all holidays of a year in a {@link Region}.
* @param year
* @param region
* @returns {Array.<Holiday>}
*/
function getHolidays(year, region) {
let y;
if (typeof year === 'string') {
y = parseInt(year, 10);
}
else {
y = year;
}
checkRegion(region);
return getHolidaysOfYear(y, region);
}
/**
*
* @param {number} year
* @param region
* @returns {number[]}
* @private
*/
function getHolidaysAsUtcTimestamps(year, region) {
const holidays = getHolidaysOfYear(year, region);
return holidays.map((holiday) => toUtcTimestamp(holiday.date));
}
/**
*
* @param {number} year
* @param region
* @returns {{objects: Array.<Holiday>, integers}}
* @private
*/
function getHolidaysOfYear(year, region) {
const easterDate = getEasterDate(year);
const karfreitag = addDays(new Date(easterDate.getTime()), -2);
const ostermontag = addDays(new Date(easterDate.getTime()), 1);
const christiHimmelfahrt = addDays(new Date(easterDate.getTime()), 39);
const pfingstsonntag = addDays(new Date(easterDate.getTime()), 49);
const pfingstmontag = addDays(new Date(easterDate.getTime()), 50);
const holidays = [
...getCommonHolidays(year),
newHoliday('KARFREITAG', karfreitag),
newHoliday('OSTERMONTAG', ostermontag),
newHoliday('CHRISTIHIMMELFAHRT', christiHimmelfahrt),
newHoliday('PFINGSTMONTAG', pfingstmontag),
];
addHeiligeDreiKoenige(year, region, holidays);
addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, holidays);
addFronleichnam(region, easterDate, holidays);
addMariaeHimmelfahrt(year, region, holidays);
addReformationstag(year, region, holidays);
addAllerheiligen(year, region, holidays);
addBussUndBetttag(year, region, holidays);
addWeltkindertag(year, region, holidays);
addWeltfrauenTag(year, region, holidays);
addRegionalHolidays(year, region, holidays);
return holidays.sort((a, b) => a.date.getTime() - b.date.getTime());
}
function getCommonHolidays(year) {
return [
newHoliday('NEUJAHRSTAG', makeDate(year, 1, 1)),
newHoliday('TAG_DER_ARBEIT', makeDate(year, 5, 1)),
newHoliday('DEUTSCHEEINHEIT', makeDate(year, 10, 3)),
newHoliday('ERSTERWEIHNACHTSFEIERTAG', makeDate(year, 12, 25)),
newHoliday('ZWEITERWEIHNACHTSFEIERTAG', makeDate(year, 12, 26)),
];
}
function addRegionalHolidays(year, region, feiertageObjects) {
if (region === 'AUGSBURG') {
feiertageObjects.push(newHoliday('AUGSBURGER_FRIEDENSFEST', makeDate(year, 8, 8)));
}
}
function addHeiligeDreiKoenige(year, region, feiertageObjects) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ST' ||
region === 'ALL') {
feiertageObjects.push(newHoliday('HEILIGEDREIKOENIGE', makeDate(year, 1, 6)));
}
}
function addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, feiertageObjects) {
if (region === 'BB' || region === 'ALL') {
feiertageObjects.push(newHoliday('OSTERSONNTAG', easterDate), newHoliday('PFINGSTSONNTAG', pfingstsonntag));
}
}
function addFronleichnam(region, easterDate, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'HE' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
const fronleichnam = addDays(new Date(easterDate.getTime()), 60);
holidays.push(newHoliday('FRONLEICHNAM', fronleichnam));
}
}
function addMariaeHimmelfahrt(year, region, holidays) {
if (region === 'SL' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ALL') {
holidays.push(newHoliday('MARIAHIMMELFAHRT', makeDate(year, 8, 15)));
}
}
function addReformationstag(year, region, holidays) {
if (year === 2017 ||
region === 'NI' ||
region === 'BB' ||
region === 'HB' ||
region === 'HH' ||
region === 'MV' ||
region === 'SN' ||
region === 'ST' ||
region === 'TH' ||
region === 'SH' ||
region === 'ALL') {
holidays.push(newHoliday('REFORMATIONSTAG', makeDate(year, 10, 31)));
}
}
function addAllerheiligen(year, region, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
holidays.push(newHoliday('ALLERHEILIGEN', makeDate(year, 11, 1)));
}
}
function addBussUndBetttag(year, region, holidays) {
if (region === 'SN' || region === 'ALL') {
// @todo write test
const bussbettag = getBussBettag(year);
holidays.push(newHoliday('BUBETAG', makeDate(bussbettag.getUTCFullYear(), bussbettag.getUTCMonth() + 1, bussbettag.getUTCDate())));
}
}
function addWeltkindertag(year, region, holidays) {
if (year >= 2019 && (region === 'TH' || region === 'ALL')) {
holidays.push(newHoliday('WELTKINDERTAG', makeDate(year, 9, 20)));
}
}
function addWeltfrauenTag(year, region, feiertageObjects) {
if (year <= 2018) {
return;
}
if (region === 'BE' || region === 'ALL') {
// in Berlin ist der Weltfrauentag ein Feiertag seit 2018
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
if (region === 'MV' && year >= 2023) {
// in MV wird der Weltfrauentag erst ab 2023 eingeführt
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
}
/**
* Calculates the Easter date of a given year.
* @param year {number}
* @returns {Date} Easter date
* @private
*/
function getEasterDate(year) {
const C = Math.floor(year / 100);
// tslint:disable:binary-expression-operand-order
// tslint generates false positives in the following blocks
const N = year - 19 * Math.floor(year / 19);
const K = Math.floor((C - 17) / 25);
let I = C - Math.floor(C / 4) - Math.floor((C - K) / 3) + 19 * N + 15;
I -= 30 * Math.floor(I / 30);
I -=
Math.floor(I / 28) *
(1 -
Math.floor(I / 28) *
Math.floor(29 / (I + 1)) *
Math.floor((21 - N) / 11));
let J = year + Math.floor(year / 4) + I + 2 - C + Math.floor(C / 4);
J -= 7 * Math.floor(J / 7);
const L = I - J;
const M = 3 + Math.floor((L + 40) / 44);
const D = L + 28 - 31 * Math.floor(M / 4);
// tslint:enable:binary-expression-operand-order
return new Date(year, M - 1, D);
}
/**
* Computes the "Buss- und Bettag"'s date.
* @param jahr {number}
* @returns {Date} the year's "Buss- und Bettag" date
* @private
*/
function getBussBettag(jahr) {
const weihnachten = new Date(jahr, 11, 25, 12, 0, 0);
const ersterAdventOffset = 32;
let wochenTagOffset = weihnachten.getDay() % 7;
if (wochenTagOffset === 0) {
wochenTagOffset = 7;
}
const tageVorWeihnachten = wochenTagOffset + ersterAdventOffset;
let bbtag = new Date(weihnachten.getTime());
bbtag = addDays(bbtag, -tageVorWeihnachten);
return bbtag;
}
/**
* Adds {@code days} days to the given {@link Date}.
* @param date
* @param days
* @returns {Date}
* @private
*/
function addDays(date, days) {
const changedDate = new Date(date);
changedDate.setDate(date.getDate() + days);
return changedDate;
}
/**
* Creates a new {@link Date}.
* @param year
* @param naturalMonth month (1-12)
* @param day
* @returns {Date}
* @private
*/
function makeDate(year, naturalMonth, day) {
return new Date(year, naturalMonth - 1, day);
}
/**
*
* @param name
* @param date
* @returns {Holiday}
* @private
*/
function newHoliday(name, date) {
return {
name,
date,
dateString: localeDateObjectToDateString(date),
trans(lang = currentLanguage) {
console.warn('FeiertageJs: You are using "Holiday.trans() method. This will be replaced in the next major version with translate()"');
return this.translate(lang);
},
translate(lang = currentLanguage) {
return lang === undefined || lang === null
? undefined
: translations[lang][this.name];
},
getNormalizedDate() {
return toUtcTimestamp(this.date);
},
equals(otherDate) {
const dateString = localeDateObjectToDateString(otherDate);
return this.dateString === dateString;
},
};
}
/**
*
* @param date
* @returns {string}
* @private
*/
function localeDateObjectToDateString(date) {
const normalizedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
normalizedDate.setUTCHours(0, 0, 0, 0);
return normalizedDate.toISOString().slice(0, 10);
}
/**
* Returns the UTC timestamp of the given date with hours, minutes, seconds, and milliseconds set to zero.
* @param date
* @returns {number} UTC timestamp
*/
function toUtcTimestamp(date) {
const internalDate = new Date(date);
internalDate.setHours(0, 0, 0, 0);
return internalDate.getTime();
}
export { addTranslation, getHolidayByDate, getHolidays, getLanguage, isHoliday, isSpecificHoliday, isSunOrHoliday, setLanguage };
//# sourceMappingURL=feiertage.esm.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"feiertage.esm.js","sources":["../src/german-translations.ts","../src/holiday-type.ts","../src/regions.ts","../src/feiertage.ts"],"sourcesContent":["import { TranslationTable } from './feiertage';\n\nexport const germanTranslations: TranslationTable = {\n NEUJAHRSTAG: 'Neujahrstag',\n HEILIGEDREIKOENIGE: 'Heilige Drei Könige',\n KARFREITAG: 'Karfreitag',\n OSTERSONNTAG: 'Ostersonntag',\n OSTERMONTAG: 'Ostermontag',\n TAG_DER_ARBEIT: 'Tag der Arbeit',\n CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',\n PFINGSTSONNTAG: 'Pfingstsonntag',\n PFINGSTMONTAG: 'Pfingstmontag',\n FRONLEICHNAM: 'Fronleichnam',\n MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',\n DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',\n REFORMATIONSTAG: 'Reformationstag',\n ALLERHEILIGEN: 'Allerheiligen',\n BUBETAG: 'Buß- und Bettag',\n ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',\n ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',\n WELTKINDERTAG: 'Weltkindertag',\n WELTFRAUENTAG: 'Weltfrauentag',\n AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',\n};\n","export type HolidayType =\n | 'NEUJAHRSTAG'\n | 'HEILIGEDREIKOENIGE'\n | 'KARFREITAG'\n | 'OSTERSONNTAG'\n | 'OSTERMONTAG'\n | 'TAG_DER_ARBEIT'\n | 'CHRISTIHIMMELFAHRT'\n | 'MARIAHIMMELFAHRT'\n | 'PFINGSTSONNTAG'\n | 'PFINGSTMONTAG'\n | 'FRONLEICHNAM'\n | 'DEUTSCHEEINHEIT'\n | 'REFORMATIONSTAG'\n | 'ALLERHEILIGEN'\n | 'BUBETAG'\n | 'ERSTERWEIHNACHTSFEIERTAG'\n | 'ZWEITERWEIHNACHTSFEIERTAG'\n | 'WELTKINDERTAG'\n | 'WELTFRAUENTAG'\n | 'AUGSBURGER_FRIEDENSFEST';\n\nexport const allHolidays: HolidayType[] = [\n 'NEUJAHRSTAG',\n 'HEILIGEDREIKOENIGE',\n 'KARFREITAG',\n 'OSTERSONNTAG',\n 'OSTERMONTAG',\n 'TAG_DER_ARBEIT',\n 'CHRISTIHIMMELFAHRT',\n 'MARIAHIMMELFAHRT',\n 'PFINGSTSONNTAG',\n 'PFINGSTMONTAG',\n 'FRONLEICHNAM',\n 'DEUTSCHEEINHEIT',\n 'REFORMATIONSTAG',\n 'ALLERHEILIGEN',\n 'BUBETAG',\n 'ERSTERWEIHNACHTSFEIERTAG',\n 'ZWEITERWEIHNACHTSFEIERTAG',\n 'WELTKINDERTAG',\n 'WELTFRAUENTAG',\n 'AUGSBURGER_FRIEDENSFEST',\n];\n","export type Region =\n | 'BW' // Baden-Württemberg\n | 'BY' // Bayern\n | 'BE' // Berlin\n | 'BB' // Brandenburg\n | 'HB' // Bremen\n | 'HE' // Hessen\n | 'HH' // Hamburg\n | 'MV' // Mecklenburg-Vorpommern\n | 'NI' // Niedersachsen\n | 'NW' // Nordrhein-Westfalen\n | 'RP' // Rheinland-Pfalz\n | 'SL' // Saarland\n | 'SN' // Sachsen\n | 'ST' // Sachsen-Anhalt\n | 'SH' // Schleswig-Holstein\n | 'TH' // Thüringen\n | 'BUND' // Gesamt-Deutschland\n // Custom regions with local holidays (incompelte) !\n | 'AUGSBURG'\n | 'ALL';\n\nexport const allRegions: Region[] = [\n 'BW',\n 'BY',\n 'BE',\n 'BB',\n 'HB',\n 'HE',\n 'HH',\n 'MV',\n 'NI',\n 'NW',\n 'RP',\n 'SL',\n 'SN',\n 'ST',\n 'SH',\n 'TH',\n 'BUND',\n 'AUGSBURG',\n 'ALL',\n];\n","/*!\n * feiertage.js\n * @repository https://github.com/sfakir/feiertagejs\n * @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md\n *\n * Copyright 2015-2021 Simon Fakir\n * Released under the MIT license\n */\n\n//\n// Additional readings\n// - how to format a javascript date: http://blog.stevenlevithan.com/archives/date-time-format\n// - the right javascript date: http://stackoverflow.com/questions/10286204/the-right-json-date-format\n//\n\nimport { germanTranslations } from './german-translations';\nimport { Holiday } from './holiday';\nimport { allHolidays, HolidayType } from './holiday-type';\nimport { allRegions, Region } from './regions';\n\n// translations\n\nconst defaultLanguage = 'de';\nlet currentLanguage: string = defaultLanguage;\n\n/**\n * Map of {@link HolidayType} to translation string.\n */\nexport type TranslationTable = { [key in HolidayType]?: string };\n\nconst translations: { [key: string]: TranslationTable } = {\n de: germanTranslations,\n};\n\n/**\n * adds a translation for the holidays (e.g. english).\n * This also allows to override the German names.\n * Hint: Interpolates German for missing translations\n * @param {string} isoCode of the new language\n * @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg\n */\nexport function addTranslation(\n isoCode: string,\n newTranslation: TranslationTable,\n): void {\n const code = isoCode.toLowerCase();\n const defaultTranslation = translations[defaultLanguage];\n let missingFields = false;\n\n // fill new Translation with default Language\n for (const holiday of allHolidays) {\n if (!newTranslation[holiday]) {\n missingFields = true;\n newTranslation[holiday] = defaultTranslation[holiday];\n }\n }\n if (missingFields) {\n console.warn(\n '[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback',\n );\n }\n\n translations[code] = newTranslation;\n}\n\n/**\n * Set a language to default language\n * @param {string} isoCode\n */\nexport function setLanguage(isoCode: string): void {\n const code = isoCode.toLowerCase();\n if (!translations[code])Line truncated
+476
View File
@@ -0,0 +1,476 @@
const germanTranslations = {
NEUJAHRSTAG: 'Neujahrstag',
HEILIGEDREIKOENIGE: 'Heilige Drei Könige',
KARFREITAG: 'Karfreitag',
OSTERSONNTAG: 'Ostersonntag',
OSTERMONTAG: 'Ostermontag',
TAG_DER_ARBEIT: 'Tag der Arbeit',
CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',
PFINGSTSONNTAG: 'Pfingstsonntag',
PFINGSTMONTAG: 'Pfingstmontag',
FRONLEICHNAM: 'Fronleichnam',
MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',
DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',
REFORMATIONSTAG: 'Reformationstag',
ALLERHEILIGEN: 'Allerheiligen',
BUBETAG: 'Buß- und Bettag',
ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',
ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',
WELTKINDERTAG: 'Weltkindertag',
WELTFRAUENTAG: 'Weltfrauentag',
AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',
};
const allHolidays = [
'NEUJAHRSTAG',
'HEILIGEDREIKOENIGE',
'KARFREITAG',
'OSTERSONNTAG',
'OSTERMONTAG',
'TAG_DER_ARBEIT',
'CHRISTIHIMMELFAHRT',
'MARIAHIMMELFAHRT',
'PFINGSTSONNTAG',
'PFINGSTMONTAG',
'FRONLEICHNAM',
'DEUTSCHEEINHEIT',
'REFORMATIONSTAG',
'ALLERHEILIGEN',
'BUBETAG',
'ERSTERWEIHNACHTSFEIERTAG',
'ZWEITERWEIHNACHTSFEIERTAG',
'WELTKINDERTAG',
'WELTFRAUENTAG',
'AUGSBURGER_FRIEDENSFEST',
];
const allRegions = [
'BW',
'BY',
'BE',
'BB',
'HB',
'HE',
'HH',
'MV',
'NI',
'NW',
'RP',
'SL',
'SN',
'ST',
'SH',
'TH',
'BUND',
'AUGSBURG',
'ALL',
];
/*!
* feiertage.js
* @repository https://github.com/sfakir/feiertagejs
* @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md
*
* Copyright 2015-2021 Simon Fakir
* Released under the MIT license
*/
// translations
const defaultLanguage = 'de';
let currentLanguage = defaultLanguage;
const translations = {
de: germanTranslations,
};
/**
* adds a translation for the holidays (e.g. english).
* This also allows to override the German names.
* Hint: Interpolates German for missing translations
* @param {string} isoCode of the new language
* @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg
*/
function addTranslation(isoCode, newTranslation) {
const code = isoCode.toLowerCase();
const defaultTranslation = translations[defaultLanguage];
let missingFields = false;
// fill new Translation with default Language
for (const holiday of allHolidays) {
if (!newTranslation[holiday]) {
missingFields = true;
newTranslation[holiday] = defaultTranslation[holiday];
}
}
if (missingFields) {
console.warn('[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback');
}
translations[code] = newTranslation;
}
/**
* Set a language to default language
* @param {string} isoCode
*/
function setLanguage(isoCode) {
const code = isoCode.toLowerCase();
if (!translations[code]) {
throw new TypeError(`[feiertagejs] tried to set language to ${code} but the translation is missing. Please use addTranslation(isoCode,object) first`);
}
currentLanguage = isoCode;
}
/**
* Get currently set language
* @returns {string}
*/
function getLanguage() {
return currentLanguage;
}
// holidays api
/**
* Checks if a specific date is sunday or holiday.
* @param date
* @param region
* @returns {boolean}
*/
function isSunOrHoliday(date, region) {
checkRegion(region);
return date.getDay() === 0 || isHoliday(date, region);
}
/**
* Check is specific date is holiday.
* @param date
* @param {Region} region two character {@link Region} code
* @returns {boolean}
*/
function isHoliday(date, region) {
checkRegion(region);
const year = date.getFullYear();
const internalDate = toUtcTimestamp(date);
const holidays = getHolidaysAsUtcTimestamps(year, region);
return holidays.indexOf(internalDate) !== -1;
}
function getHolidayByDate(date, region = 'ALL') {
checkRegion(region);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
return holidays.find((holiday) => holiday.equals(date));
}
// additional runtime checks
/**
* Checks if the given region is a valid {@link Region}.
*
* @param region {@link Region} to check
* @throws {Error}
* @private
*/
function checkRegion(region) {
if (region === null || region === undefined) {
throw new Error(`Region must not be undefined or null`);
}
if (allRegions.indexOf(region) === -1) {
throw new Error(`Invalid region: ${region}! Must be one of ${allRegions.toString()}`);
}
}
/**
* Checks if the given holidayName is a valid {@link HolidayType}.
* @param holidayName {@link HolidayType} to check
* @throws {Error}
* @private
*/
function checkHolidayType(holidayName) {
if (holidayName === null || holidayName === undefined) {
throw new TypeError('holidayName must not be null or undefined');
}
if (allHolidays.indexOf(holidayName) === -1) {
throw new Error(`feiertage.js: invalid holiday type "${holidayName}"! Must be one of ${allHolidays.toString()}`);
}
}
function isSpecificHoliday(date, holidayName, region = 'ALL') {
checkRegion(region);
checkHolidayType(holidayName);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
const foundHoliday = holidays.find((holiday) => holiday.equals(date));
if (!foundHoliday) {
return false;
}
return foundHoliday.name === holidayName;
}
/**
* Returns all holidays of a year in a {@link Region}.
* @param year
* @param region
* @returns {Array.<Holiday>}
*/
function getHolidays(year, region) {
let y;
if (typeof year === 'string') {
y = parseInt(year, 10);
}
else {
y = year;
}
checkRegion(region);
return getHolidaysOfYear(y, region);
}
/**
*
* @param {number} year
* @param region
* @returns {number[]}
* @private
*/
function getHolidaysAsUtcTimestamps(year, region) {
const holidays = getHolidaysOfYear(year, region);
return holidays.map((holiday) => toUtcTimestamp(holiday.date));
}
/**
*
* @param {number} year
* @param region
* @returns {{objects: Array.<Holiday>, integers}}
* @private
*/
function getHolidaysOfYear(year, region) {
const easterDate = getEasterDate(year);
const karfreitag = addDays(new Date(easterDate.getTime()), -2);
const ostermontag = addDays(new Date(easterDate.getTime()), 1);
const christiHimmelfahrt = addDays(new Date(easterDate.getTime()), 39);
const pfingstsonntag = addDays(new Date(easterDate.getTime()), 49);
const pfingstmontag = addDays(new Date(easterDate.getTime()), 50);
const holidays = [
...getCommonHolidays(year),
newHoliday('KARFREITAG', karfreitag),
newHoliday('OSTERMONTAG', ostermontag),
newHoliday('CHRISTIHIMMELFAHRT', christiHimmelfahrt),
newHoliday('PFINGSTMONTAG', pfingstmontag),
];
addHeiligeDreiKoenige(year, region, holidays);
addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, holidays);
addFronleichnam(region, easterDate, holidays);
addMariaeHimmelfahrt(year, region, holidays);
addReformationstag(year, region, holidays);
addAllerheiligen(year, region, holidays);
addBussUndBetttag(year, region, holidays);
addWeltkindertag(year, region, holidays);
addWeltfrauenTag(year, region, holidays);
addRegionalHolidays(year, region, holidays);
return holidays.sort((a, b) => a.date.getTime() - b.date.getTime());
}
function getCommonHolidays(year) {
return [
newHoliday('NEUJAHRSTAG', makeDate(year, 1, 1)),
newHoliday('TAG_DER_ARBEIT', makeDate(year, 5, 1)),
newHoliday('DEUTSCHEEINHEIT', makeDate(year, 10, 3)),
newHoliday('ERSTERWEIHNACHTSFEIERTAG', makeDate(year, 12, 25)),
newHoliday('ZWEITERWEIHNACHTSFEIERTAG', makeDate(year, 12, 26)),
];
}
function addRegionalHolidays(year, region, feiertageObjects) {
if (region === 'AUGSBURG') {
feiertageObjects.push(newHoliday('AUGSBURGER_FRIEDENSFEST', makeDate(year, 8, 8)));
}
}
function addHeiligeDreiKoenige(year, region, feiertageObjects) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ST' ||
region === 'ALL') {
feiertageObjects.push(newHoliday('HEILIGEDREIKOENIGE', makeDate(year, 1, 6)));
}
}
function addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, feiertageObjects) {
if (region === 'BB' || region === 'ALL') {
feiertageObjects.push(newHoliday('OSTERSONNTAG', easterDate), newHoliday('PFINGSTSONNTAG', pfingstsonntag));
}
}
function addFronleichnam(region, easterDate, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'HE' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
const fronleichnam = addDays(new Date(easterDate.getTime()), 60);
holidays.push(newHoliday('FRONLEICHNAM', fronleichnam));
}
}
function addMariaeHimmelfahrt(year, region, holidays) {
if (region === 'SL' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ALL') {
holidays.push(newHoliday('MARIAHIMMELFAHRT', makeDate(year, 8, 15)));
}
}
function addReformationstag(year, region, holidays) {
if (year === 2017 ||
region === 'NI' ||
region === 'BB' ||
region === 'HB' ||
region === 'HH' ||
region === 'MV' ||
region === 'SN' ||
region === 'ST' ||
region === 'TH' ||
region === 'SH' ||
region === 'ALL') {
holidays.push(newHoliday('REFORMATIONSTAG', makeDate(year, 10, 31)));
}
}
function addAllerheiligen(year, region, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
holidays.push(newHoliday('ALLERHEILIGEN', makeDate(year, 11, 1)));
}
}
function addBussUndBetttag(year, region, holidays) {
if (region === 'SN' || region === 'ALL') {
// @todo write test
const bussbettag = getBussBettag(year);
holidays.push(newHoliday('BUBETAG', makeDate(bussbettag.getUTCFullYear(), bussbettag.getUTCMonth() + 1, bussbettag.getUTCDate())));
}
}
function addWeltkindertag(year, region, holidays) {
if (year >= 2019 && (region === 'TH' || region === 'ALL')) {
holidays.push(newHoliday('WELTKINDERTAG', makeDate(year, 9, 20)));
}
}
function addWeltfrauenTag(year, region, feiertageObjects) {
if (year <= 2018) {
return;
}
if (region === 'BE' || region === 'ALL') {
// in Berlin ist der Weltfrauentag ein Feiertag seit 2018
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
if (region === 'MV' && year >= 2023) {
// in MV wird der Weltfrauentag erst ab 2023 eingeführt
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
}
/**
* Calculates the Easter date of a given year.
* @param year {number}
* @returns {Date} Easter date
* @private
*/
function getEasterDate(year) {
const C = Math.floor(year / 100);
// tslint:disable:binary-expression-operand-order
// tslint generates false positives in the following blocks
const N = year - 19 * Math.floor(year / 19);
const K = Math.floor((C - 17) / 25);
let I = C - Math.floor(C / 4) - Math.floor((C - K) / 3) + 19 * N + 15;
I -= 30 * Math.floor(I / 30);
I -=
Math.floor(I / 28) *
(1 -
Math.floor(I / 28) *
Math.floor(29 / (I + 1)) *
Math.floor((21 - N) / 11));
let J = year + Math.floor(year / 4) + I + 2 - C + Math.floor(C / 4);
J -= 7 * Math.floor(J / 7);
const L = I - J;
const M = 3 + Math.floor((L + 40) / 44);
const D = L + 28 - 31 * Math.floor(M / 4);
// tslint:enable:binary-expression-operand-order
return new Date(year, M - 1, D);
}
/**
* Computes the "Buss- und Bettag"'s date.
* @param jahr {number}
* @returns {Date} the year's "Buss- und Bettag" date
* @private
*/
function getBussBettag(jahr) {
const weihnachten = new Date(jahr, 11, 25, 12, 0, 0);
const ersterAdventOffset = 32;
let wochenTagOffset = weihnachten.getDay() % 7;
if (wochenTagOffset === 0) {
wochenTagOffset = 7;
}
const tageVorWeihnachten = wochenTagOffset + ersterAdventOffset;
let bbtag = new Date(weihnachten.getTime());
bbtag = addDays(bbtag, -tageVorWeihnachten);
return bbtag;
}
/**
* Adds {@code days} days to the given {@link Date}.
* @param date
* @param days
* @returns {Date}
* @private
*/
function addDays(date, days) {
const changedDate = new Date(date);
changedDate.setDate(date.getDate() + days);
return changedDate;
}
/**
* Creates a new {@link Date}.
* @param year
* @param naturalMonth month (1-12)
* @param day
* @returns {Date}
* @private
*/
function makeDate(year, naturalMonth, day) {
return new Date(year, naturalMonth - 1, day);
}
/**
*
* @param name
* @param date
* @returns {Holiday}
* @private
*/
function newHoliday(name, date) {
return {
name,
date,
dateString: localeDateObjectToDateString(date),
trans(lang = currentLanguage) {
console.warn('FeiertageJs: You are using "Holiday.trans() method. This will be replaced in the next major version with translate()"');
return this.translate(lang);
},
translate(lang = currentLanguage) {
return lang === undefined || lang === null
? undefined
: translations[lang][this.name];
},
getNormalizedDate() {
return toUtcTimestamp(this.date);
},
equals(otherDate) {
const dateString = localeDateObjectToDateString(otherDate);
return this.dateString === dateString;
},
};
}
/**
*
* @param date
* @returns {string}
* @private
*/
function localeDateObjectToDateString(date) {
const normalizedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
normalizedDate.setUTCHours(0, 0, 0, 0);
return normalizedDate.toISOString().slice(0, 10);
}
/**
* Returns the UTC timestamp of the given date with hours, minutes, seconds, and milliseconds set to zero.
* @param date
* @returns {number} UTC timestamp
*/
function toUtcTimestamp(date) {
const internalDate = new Date(date);
internalDate.setHours(0, 0, 0, 0);
return internalDate.getTime();
}
export { addTranslation, getHolidayByDate, getHolidays, getLanguage, isHoliday, isSpecificHoliday, isSunOrHoliday, setLanguage };
//# sourceMappingURL=feiertage.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"feiertage.js","sources":["../src/german-translations.ts","../src/holiday-type.ts","../src/regions.ts","../src/feiertage.ts"],"sourcesContent":["import { TranslationTable } from './feiertage';\n\nexport const germanTranslations: TranslationTable = {\n NEUJAHRSTAG: 'Neujahrstag',\n HEILIGEDREIKOENIGE: 'Heilige Drei Könige',\n KARFREITAG: 'Karfreitag',\n OSTERSONNTAG: 'Ostersonntag',\n OSTERMONTAG: 'Ostermontag',\n TAG_DER_ARBEIT: 'Tag der Arbeit',\n CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',\n PFINGSTSONNTAG: 'Pfingstsonntag',\n PFINGSTMONTAG: 'Pfingstmontag',\n FRONLEICHNAM: 'Fronleichnam',\n MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',\n DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',\n REFORMATIONSTAG: 'Reformationstag',\n ALLERHEILIGEN: 'Allerheiligen',\n BUBETAG: 'Buß- und Bettag',\n ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',\n ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',\n WELTKINDERTAG: 'Weltkindertag',\n WELTFRAUENTAG: 'Weltfrauentag',\n AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',\n};\n","export type HolidayType =\n | 'NEUJAHRSTAG'\n | 'HEILIGEDREIKOENIGE'\n | 'KARFREITAG'\n | 'OSTERSONNTAG'\n | 'OSTERMONTAG'\n | 'TAG_DER_ARBEIT'\n | 'CHRISTIHIMMELFAHRT'\n | 'MARIAHIMMELFAHRT'\n | 'PFINGSTSONNTAG'\n | 'PFINGSTMONTAG'\n | 'FRONLEICHNAM'\n | 'DEUTSCHEEINHEIT'\n | 'REFORMATIONSTAG'\n | 'ALLERHEILIGEN'\n | 'BUBETAG'\n | 'ERSTERWEIHNACHTSFEIERTAG'\n | 'ZWEITERWEIHNACHTSFEIERTAG'\n | 'WELTKINDERTAG'\n | 'WELTFRAUENTAG'\n | 'AUGSBURGER_FRIEDENSFEST';\n\nexport const allHolidays: HolidayType[] = [\n 'NEUJAHRSTAG',\n 'HEILIGEDREIKOENIGE',\n 'KARFREITAG',\n 'OSTERSONNTAG',\n 'OSTERMONTAG',\n 'TAG_DER_ARBEIT',\n 'CHRISTIHIMMELFAHRT',\n 'MARIAHIMMELFAHRT',\n 'PFINGSTSONNTAG',\n 'PFINGSTMONTAG',\n 'FRONLEICHNAM',\n 'DEUTSCHEEINHEIT',\n 'REFORMATIONSTAG',\n 'ALLERHEILIGEN',\n 'BUBETAG',\n 'ERSTERWEIHNACHTSFEIERTAG',\n 'ZWEITERWEIHNACHTSFEIERTAG',\n 'WELTKINDERTAG',\n 'WELTFRAUENTAG',\n 'AUGSBURGER_FRIEDENSFEST',\n];\n","export type Region =\n | 'BW' // Baden-Württemberg\n | 'BY' // Bayern\n | 'BE' // Berlin\n | 'BB' // Brandenburg\n | 'HB' // Bremen\n | 'HE' // Hessen\n | 'HH' // Hamburg\n | 'MV' // Mecklenburg-Vorpommern\n | 'NI' // Niedersachsen\n | 'NW' // Nordrhein-Westfalen\n | 'RP' // Rheinland-Pfalz\n | 'SL' // Saarland\n | 'SN' // Sachsen\n | 'ST' // Sachsen-Anhalt\n | 'SH' // Schleswig-Holstein\n | 'TH' // Thüringen\n | 'BUND' // Gesamt-Deutschland\n // Custom regions with local holidays (incompelte) !\n | 'AUGSBURG'\n | 'ALL';\n\nexport const allRegions: Region[] = [\n 'BW',\n 'BY',\n 'BE',\n 'BB',\n 'HB',\n 'HE',\n 'HH',\n 'MV',\n 'NI',\n 'NW',\n 'RP',\n 'SL',\n 'SN',\n 'ST',\n 'SH',\n 'TH',\n 'BUND',\n 'AUGSBURG',\n 'ALL',\n];\n","/*!\n * feiertage.js\n * @repository https://github.com/sfakir/feiertagejs\n * @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md\n *\n * Copyright 2015-2021 Simon Fakir\n * Released under the MIT license\n */\n\n//\n// Additional readings\n// - how to format a javascript date: http://blog.stevenlevithan.com/archives/date-time-format\n// - the right javascript date: http://stackoverflow.com/questions/10286204/the-right-json-date-format\n//\n\nimport { germanTranslations } from './german-translations';\nimport { Holiday } from './holiday';\nimport { allHolidays, HolidayType } from './holiday-type';\nimport { allRegions, Region } from './regions';\n\n// translations\n\nconst defaultLanguage = 'de';\nlet currentLanguage: string = defaultLanguage;\n\n/**\n * Map of {@link HolidayType} to translation string.\n */\nexport type TranslationTable = { [key in HolidayType]?: string };\n\nconst translations: { [key: string]: TranslationTable } = {\n de: germanTranslations,\n};\n\n/**\n * adds a translation for the holidays (e.g. english).\n * This also allows to override the German names.\n * Hint: Interpolates German for missing translations\n * @param {string} isoCode of the new language\n * @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg\n */\nexport function addTranslation(\n isoCode: string,\n newTranslation: TranslationTable,\n): void {\n const code = isoCode.toLowerCase();\n const defaultTranslation = translations[defaultLanguage];\n let missingFields = false;\n\n // fill new Translation with default Language\n for (const holiday of allHolidays) {\n if (!newTranslation[holiday]) {\n missingFields = true;\n newTranslation[holiday] = defaultTranslation[holiday];\n }\n }\n if (missingFields) {\n console.warn(\n '[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback',\n );\n }\n\n translations[code] = newTranslation;\n}\n\n/**\n * Set a language to default language\n * @param {string} isoCode\n */\nexport function setLanguage(isoCode: string): void {\n const code = isoCode.toLowerCase();\n if (!translations[code]) {\nLine truncated
+496
View File
@@ -0,0 +1,496 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () {
var current = global.feiertagejs;
var exports = global.feiertagejs = {};
factory(exports);
exports.noConflict = function () { global.feiertagejs = current; return exports; };
})());
})(this, (function (exports) { 'use strict';
const germanTranslations = {
NEUJAHRSTAG: 'Neujahrstag',
HEILIGEDREIKOENIGE: 'Heilige Drei Könige',
KARFREITAG: 'Karfreitag',
OSTERSONNTAG: 'Ostersonntag',
OSTERMONTAG: 'Ostermontag',
TAG_DER_ARBEIT: 'Tag der Arbeit',
CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',
PFINGSTSONNTAG: 'Pfingstsonntag',
PFINGSTMONTAG: 'Pfingstmontag',
FRONLEICHNAM: 'Fronleichnam',
MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',
DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',
REFORMATIONSTAG: 'Reformationstag',
ALLERHEILIGEN: 'Allerheiligen',
BUBETAG: 'Buß- und Bettag',
ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',
ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',
WELTKINDERTAG: 'Weltkindertag',
WELTFRAUENTAG: 'Weltfrauentag',
AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',
};
const allHolidays = [
'NEUJAHRSTAG',
'HEILIGEDREIKOENIGE',
'KARFREITAG',
'OSTERSONNTAG',
'OSTERMONTAG',
'TAG_DER_ARBEIT',
'CHRISTIHIMMELFAHRT',
'MARIAHIMMELFAHRT',
'PFINGSTSONNTAG',
'PFINGSTMONTAG',
'FRONLEICHNAM',
'DEUTSCHEEINHEIT',
'REFORMATIONSTAG',
'ALLERHEILIGEN',
'BUBETAG',
'ERSTERWEIHNACHTSFEIERTAG',
'ZWEITERWEIHNACHTSFEIERTAG',
'WELTKINDERTAG',
'WELTFRAUENTAG',
'AUGSBURGER_FRIEDENSFEST',
];
const allRegions = [
'BW',
'BY',
'BE',
'BB',
'HB',
'HE',
'HH',
'MV',
'NI',
'NW',
'RP',
'SL',
'SN',
'ST',
'SH',
'TH',
'BUND',
'AUGSBURG',
'ALL',
];
/*!
* feiertage.js
* @repository https://github.com/sfakir/feiertagejs
* @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md
*
* Copyright 2015-2021 Simon Fakir
* Released under the MIT license
*/
// translations
const defaultLanguage = 'de';
let currentLanguage = defaultLanguage;
const translations = {
de: germanTranslations,
};
/**
* adds a translation for the holidays (e.g. english).
* This also allows to override the German names.
* Hint: Interpolates German for missing translations
* @param {string} isoCode of the new language
* @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg
*/
function addTranslation(isoCode, newTranslation) {
const code = isoCode.toLowerCase();
const defaultTranslation = translations[defaultLanguage];
let missingFields = false;
// fill new Translation with default Language
for (const holiday of allHolidays) {
if (!newTranslation[holiday]) {
missingFields = true;
newTranslation[holiday] = defaultTranslation[holiday];
}
}
if (missingFields) {
console.warn('[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback');
}
translations[code] = newTranslation;
}
/**
* Set a language to default language
* @param {string} isoCode
*/
function setLanguage(isoCode) {
const code = isoCode.toLowerCase();
if (!translations[code]) {
throw new TypeError(`[feiertagejs] tried to set language to ${code} but the translation is missing. Please use addTranslation(isoCode,object) first`);
}
currentLanguage = isoCode;
}
/**
* Get currently set language
* @returns {string}
*/
function getLanguage() {
return currentLanguage;
}
// holidays api
/**
* Checks if a specific date is sunday or holiday.
* @param date
* @param region
* @returns {boolean}
*/
function isSunOrHoliday(date, region) {
checkRegion(region);
return date.getDay() === 0 || isHoliday(date, region);
}
/**
* Check is specific date is holiday.
* @param date
* @param {Region} region two character {@link Region} code
* @returns {boolean}
*/
function isHoliday(date, region) {
checkRegion(region);
const year = date.getFullYear();
const internalDate = toUtcTimestamp(date);
const holidays = getHolidaysAsUtcTimestamps(year, region);
return holidays.indexOf(internalDate) !== -1;
}
function getHolidayByDate(date, region = 'ALL') {
checkRegion(region);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
return holidays.find((holiday) => holiday.equals(date));
}
// additional runtime checks
/**
* Checks if the given region is a valid {@link Region}.
*
* @param region {@link Region} to check
* @throws {Error}
* @private
*/
function checkRegion(region) {
if (region === null || region === undefined) {
throw new Error(`Region must not be undefined or null`);
}
if (allRegions.indexOf(region) === -1) {
throw new Error(`Invalid region: ${region}! Must be one of ${allRegions.toString()}`);
}
}
/**
* Checks if the given holidayName is a valid {@link HolidayType}.
* @param holidayName {@link HolidayType} to check
* @throws {Error}
* @private
*/
function checkHolidayType(holidayName) {
if (holidayName === null || holidayName === undefined) {
throw new TypeError('holidayName must not be null or undefined');
}
if (allHolidays.indexOf(holidayName) === -1) {
throw new Error(`feiertage.js: invalid holiday type "${holidayName}"! Must be one of ${allHolidays.toString()}`);
}
}
function isSpecificHoliday(date, holidayName, region = 'ALL') {
checkRegion(region);
checkHolidayType(holidayName);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
const foundHoliday = holidays.find((holiday) => holiday.equals(date));
if (!foundHoliday) {
return false;
}
return foundHoliday.name === holidayName;
}
/**
* Returns all holidays of a year in a {@link Region}.
* @param year
* @param region
* @returns {Array.<Holiday>}
*/
function getHolidays(year, region) {
let y;
if (typeof year === 'string') {
y = parseInt(year, 10);
}
else {
y = year;
}
checkRegion(region);
return getHolidaysOfYear(y, region);
}
/**
*
* @param {number} year
* @param region
* @returns {number[]}
* @private
*/
function getHolidaysAsUtcTimestamps(year, region) {
const holidays = getHolidaysOfYear(year, region);
return holidays.map((holiday) => toUtcTimestamp(holiday.date));
}
/**
*
* @param {number} year
* @param region
* @returns {{objects: Array.<Holiday>, integers}}
* @private
*/
function getHolidaysOfYear(year, region) {
const easterDate = getEasterDate(year);
const karfreitag = addDays(new Date(easterDate.getTime()), -2);
const ostermontag = addDays(new Date(easterDate.getTime()), 1);
const christiHimmelfahrt = addDays(new Date(easterDate.getTime()), 39);
const pfingstsonntag = addDays(new Date(easterDate.getTime()), 49);
const pfingstmontag = addDays(new Date(easterDate.getTime()), 50);
const holidays = [
...getCommonHolidays(year),
newHoliday('KARFREITAG', karfreitag),
newHoliday('OSTERMONTAG', ostermontag),
newHoliday('CHRISTIHIMMELFAHRT', christiHimmelfahrt),
newHoliday('PFINGSTMONTAG', pfingstmontag),
];
addHeiligeDreiKoenige(year, region, holidays);
addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, holidays);
addFronleichnam(region, easterDate, holidays);
addMariaeHimmelfahrt(year, region, holidays);
addReformationstag(year, region, holidays);
addAllerheiligen(year, region, holidays);
addBussUndBetttag(year, region, holidays);
addWeltkindertag(year, region, holidays);
addWeltfrauenTag(year, region, holidays);
addRegionalHolidays(year, region, holidays);
return holidays.sort((a, b) => a.date.getTime() - b.date.getTime());
}
function getCommonHolidays(year) {
return [
newHoliday('NEUJAHRSTAG', makeDate(year, 1, 1)),
newHoliday('TAG_DER_ARBEIT', makeDate(year, 5, 1)),
newHoliday('DEUTSCHEEINHEIT', makeDate(year, 10, 3)),
newHoliday('ERSTERWEIHNACHTSFEIERTAG', makeDate(year, 12, 25)),
newHoliday('ZWEITERWEIHNACHTSFEIERTAG', makeDate(year, 12, 26)),
];
}
function addRegionalHolidays(year, region, feiertageObjects) {
if (region === 'AUGSBURG') {
feiertageObjects.push(newHoliday('AUGSBURGER_FRIEDENSFEST', makeDate(year, 8, 8)));
}
}
function addHeiligeDreiKoenige(year, region, feiertageObjects) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ST' ||
region === 'ALL') {
feiertageObjects.push(newHoliday('HEILIGEDREIKOENIGE', makeDate(year, 1, 6)));
}
}
function addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, feiertageObjects) {
if (region === 'BB' || region === 'ALL') {
feiertageObjects.push(newHoliday('OSTERSONNTAG', easterDate), newHoliday('PFINGSTSONNTAG', pfingstsonntag));
}
}
function addFronleichnam(region, easterDate, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'HE' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
const fronleichnam = addDays(new Date(easterDate.getTime()), 60);
holidays.push(newHoliday('FRONLEICHNAM', fronleichnam));
}
}
function addMariaeHimmelfahrt(year, region, holidays) {
if (region === 'SL' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ALL') {
holidays.push(newHoliday('MARIAHIMMELFAHRT', makeDate(year, 8, 15)));
}
}
function addReformationstag(year, region, holidays) {
if (year === 2017 ||
region === 'NI' ||
region === 'BB' ||
region === 'HB' ||
region === 'HH' ||
region === 'MV' ||
region === 'SN' ||
region === 'ST' ||
region === 'TH' ||
region === 'SH' ||
region === 'ALL') {
holidays.push(newHoliday('REFORMATIONSTAG', makeDate(year, 10, 31)));
}
}
function addAllerheiligen(year, region, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
holidays.push(newHoliday('ALLERHEILIGEN', makeDate(year, 11, 1)));
}
}
function addBussUndBetttag(year, region, holidays) {
if (region === 'SN' || region === 'ALL') {
// @todo write test
const bussbettag = getBussBettag(year);
holidays.push(newHoliday('BUBETAG', makeDate(bussbettag.getUTCFullYear(), bussbettag.getUTCMonth() + 1, bussbettag.getUTCDate())));
}
}
function addWeltkindertag(year, region, holidays) {
if (year >= 2019 && (region === 'TH' || region === 'ALL')) {
holidays.push(newHoliday('WELTKINDERTAG', makeDate(year, 9, 20)));
}
}
function addWeltfrauenTag(year, region, feiertageObjects) {
if (year <= 2018) {
return;
}
if (region === 'BE' || region === 'ALL') {
// in Berlin ist der Weltfrauentag ein Feiertag seit 2018
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
if (region === 'MV' && year >= 2023) {
// in MV wird der Weltfrauentag erst ab 2023 eingeführt
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
}
/**
* Calculates the Easter date of a given year.
* @param year {number}
* @returns {Date} Easter date
* @private
*/
function getEasterDate(year) {
const C = Math.floor(year / 100);
// tslint:disable:binary-expression-operand-order
// tslint generates false positives in the following blocks
const N = year - 19 * Math.floor(year / 19);
const K = Math.floor((C - 17) / 25);
let I = C - Math.floor(C / 4) - Math.floor((C - K) / 3) + 19 * N + 15;
I -= 30 * Math.floor(I / 30);
I -=
Math.floor(I / 28) *
(1 -
Math.floor(I / 28) *
Math.floor(29 / (I + 1)) *
Math.floor((21 - N) / 11));
let J = year + Math.floor(year / 4) + I + 2 - C + Math.floor(C / 4);
J -= 7 * Math.floor(J / 7);
const L = I - J;
const M = 3 + Math.floor((L + 40) / 44);
const D = L + 28 - 31 * Math.floor(M / 4);
// tslint:enable:binary-expression-operand-order
return new Date(year, M - 1, D);
}
/**
* Computes the "Buss- und Bettag"'s date.
* @param jahr {number}
* @returns {Date} the year's "Buss- und Bettag" date
* @private
*/
function getBussBettag(jahr) {
const weihnachten = new Date(jahr, 11, 25, 12, 0, 0);
const ersterAdventOffset = 32;
let wochenTagOffset = weihnachten.getDay() % 7;
if (wochenTagOffset === 0) {
wochenTagOffset = 7;
}
const tageVorWeihnachten = wochenTagOffset + ersterAdventOffset;
let bbtag = new Date(weihnachten.getTime());
bbtag = addDays(bbtag, -tageVorWeihnachten);
return bbtag;
}
/**
* Adds {@code days} days to the given {@link Date}.
* @param date
* @param days
* @returns {Date}
* @private
*/
function addDays(date, days) {
const changedDate = new Date(date);
changedDate.setDate(date.getDate() + days);
return changedDate;
}
/**
* Creates a new {@link Date}.
* @param year
* @param naturalMonth month (1-12)
* @param day
* @returns {Date}
* @private
*/
function makeDate(year, naturalMonth, day) {
return new Date(year, naturalMonth - 1, day);
}
/**
*
* @param name
* @param date
* @returns {Holiday}
* @private
*/
function newHoliday(name, date) {
return {
name,
date,
dateString: localeDateObjectToDateString(date),
trans(lang = currentLanguage) {
console.warn('FeiertageJs: You are using "Holiday.trans() method. This will be replaced in the next major version with translate()"');
return this.translate(lang);
},
translate(lang = currentLanguage) {
return lang === undefined || lang === null
? undefined
: translations[lang][this.name];
},
getNormalizedDate() {
return toUtcTimestamp(this.date);
},
equals(otherDate) {
const dateString = localeDateObjectToDateString(otherDate);
return this.dateString === dateString;
},
};
}
/**
*
* @param date
* @returns {string}
* @private
*/
function localeDateObjectToDateString(date) {
const normalizedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
normalizedDate.setUTCHours(0, 0, 0, 0);
return normalizedDate.toISOString().slice(0, 10);
}
/**
* Returns the UTC timestamp of the given date with hours, minutes, seconds, and milliseconds set to zero.
* @param date
* @returns {number} UTC timestamp
*/
function toUtcTimestamp(date) {
const internalDate = new Date(date);
internalDate.setHours(0, 0, 0, 0);
return internalDate.getTime();
}
exports.addTranslation = addTranslation;
exports.getHolidayByDate = getHolidayByDate;
exports.getHolidays = getHolidays;
exports.getLanguage = getLanguage;
exports.isHoliday = isHoliday;
exports.isSpecificHoliday = isSpecificHoliday;
exports.isSunOrHoliday = isSunOrHoliday;
exports.setLanguage = setLanguage;
}));
//# sourceMappingURL=feiertage.umd.cjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"feiertage.umd.cjs","sources":["../src/german-translations.ts","../src/holiday-type.ts","../src/regions.ts","../src/feiertage.ts"],"sourcesContent":["import { TranslationTable } from './feiertage';\n\nexport const germanTranslations: TranslationTable = {\n NEUJAHRSTAG: 'Neujahrstag',\n HEILIGEDREIKOENIGE: 'Heilige Drei Könige',\n KARFREITAG: 'Karfreitag',\n OSTERSONNTAG: 'Ostersonntag',\n OSTERMONTAG: 'Ostermontag',\n TAG_DER_ARBEIT: 'Tag der Arbeit',\n CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',\n PFINGSTSONNTAG: 'Pfingstsonntag',\n PFINGSTMONTAG: 'Pfingstmontag',\n FRONLEICHNAM: 'Fronleichnam',\n MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',\n DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',\n REFORMATIONSTAG: 'Reformationstag',\n ALLERHEILIGEN: 'Allerheiligen',\n BUBETAG: 'Buß- und Bettag',\n ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',\n ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',\n WELTKINDERTAG: 'Weltkindertag',\n WELTFRAUENTAG: 'Weltfrauentag',\n AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',\n};\n","export type HolidayType =\n | 'NEUJAHRSTAG'\n | 'HEILIGEDREIKOENIGE'\n | 'KARFREITAG'\n | 'OSTERSONNTAG'\n | 'OSTERMONTAG'\n | 'TAG_DER_ARBEIT'\n | 'CHRISTIHIMMELFAHRT'\n | 'MARIAHIMMELFAHRT'\n | 'PFINGSTSONNTAG'\n | 'PFINGSTMONTAG'\n | 'FRONLEICHNAM'\n | 'DEUTSCHEEINHEIT'\n | 'REFORMATIONSTAG'\n | 'ALLERHEILIGEN'\n | 'BUBETAG'\n | 'ERSTERWEIHNACHTSFEIERTAG'\n | 'ZWEITERWEIHNACHTSFEIERTAG'\n | 'WELTKINDERTAG'\n | 'WELTFRAUENTAG'\n | 'AUGSBURGER_FRIEDENSFEST';\n\nexport const allHolidays: HolidayType[] = [\n 'NEUJAHRSTAG',\n 'HEILIGEDREIKOENIGE',\n 'KARFREITAG',\n 'OSTERSONNTAG',\n 'OSTERMONTAG',\n 'TAG_DER_ARBEIT',\n 'CHRISTIHIMMELFAHRT',\n 'MARIAHIMMELFAHRT',\n 'PFINGSTSONNTAG',\n 'PFINGSTMONTAG',\n 'FRONLEICHNAM',\n 'DEUTSCHEEINHEIT',\n 'REFORMATIONSTAG',\n 'ALLERHEILIGEN',\n 'BUBETAG',\n 'ERSTERWEIHNACHTSFEIERTAG',\n 'ZWEITERWEIHNACHTSFEIERTAG',\n 'WELTKINDERTAG',\n 'WELTFRAUENTAG',\n 'AUGSBURGER_FRIEDENSFEST',\n];\n","export type Region =\n | 'BW' // Baden-Württemberg\n | 'BY' // Bayern\n | 'BE' // Berlin\n | 'BB' // Brandenburg\n | 'HB' // Bremen\n | 'HE' // Hessen\n | 'HH' // Hamburg\n | 'MV' // Mecklenburg-Vorpommern\n | 'NI' // Niedersachsen\n | 'NW' // Nordrhein-Westfalen\n | 'RP' // Rheinland-Pfalz\n | 'SL' // Saarland\n | 'SN' // Sachsen\n | 'ST' // Sachsen-Anhalt\n | 'SH' // Schleswig-Holstein\n | 'TH' // Thüringen\n | 'BUND' // Gesamt-Deutschland\n // Custom regions with local holidays (incompelte) !\n | 'AUGSBURG'\n | 'ALL';\n\nexport const allRegions: Region[] = [\n 'BW',\n 'BY',\n 'BE',\n 'BB',\n 'HB',\n 'HE',\n 'HH',\n 'MV',\n 'NI',\n 'NW',\n 'RP',\n 'SL',\n 'SN',\n 'ST',\n 'SH',\n 'TH',\n 'BUND',\n 'AUGSBURG',\n 'ALL',\n];\n","/*!\n * feiertage.js\n * @repository https://github.com/sfakir/feiertagejs\n * @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md\n *\n * Copyright 2015-2021 Simon Fakir\n * Released under the MIT license\n */\n\n//\n// Additional readings\n// - how to format a javascript date: http://blog.stevenlevithan.com/archives/date-time-format\n// - the right javascript date: http://stackoverflow.com/questions/10286204/the-right-json-date-format\n//\n\nimport { germanTranslations } from './german-translations';\nimport { Holiday } from './holiday';\nimport { allHolidays, HolidayType } from './holiday-type';\nimport { allRegions, Region } from './regions';\n\n// translations\n\nconst defaultLanguage = 'de';\nlet currentLanguage: string = defaultLanguage;\n\n/**\n * Map of {@link HolidayType} to translation string.\n */\nexport type TranslationTable = { [key in HolidayType]?: string };\n\nconst translations: { [key: string]: TranslationTable } = {\n de: germanTranslations,\n};\n\n/**\n * adds a translation for the holidays (e.g. english).\n * This also allows to override the German names.\n * Hint: Interpolates German for missing translations\n * @param {string} isoCode of the new language\n * @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg\n */\nexport function addTranslation(\n isoCode: string,\n newTranslation: TranslationTable,\n): void {\n const code = isoCode.toLowerCase();\n const defaultTranslation = translations[defaultLanguage];\n let missingFields = false;\n\n // fill new Translation with default Language\n for (const holiday of allHolidays) {\n if (!newTranslation[holiday]) {\n missingFields = true;\n newTranslation[holiday] = defaultTranslation[holiday];\n }\n }\n if (missingFields) {\n console.warn(\n '[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback',\n );\n }\n\n translations[code] = newTranslation;\n}\n\n/**\n * Set a language to default language\n * @param {string} isoCode\n */\nexport function setLanguage(isoCode: string): void {\n const code = isoCode.toLowerCase();\n if (!translations[code]Line truncated
+496
View File
@@ -0,0 +1,496 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () {
var current = global.feiertagejs;
var exports = global.feiertagejs = {};
factory(exports);
exports.noConflict = function () { global.feiertagejs = current; return exports; };
})());
})(this, (function (exports) { 'use strict';
const germanTranslations = {
NEUJAHRSTAG: 'Neujahrstag',
HEILIGEDREIKOENIGE: 'Heilige Drei Könige',
KARFREITAG: 'Karfreitag',
OSTERSONNTAG: 'Ostersonntag',
OSTERMONTAG: 'Ostermontag',
TAG_DER_ARBEIT: 'Tag der Arbeit',
CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',
PFINGSTSONNTAG: 'Pfingstsonntag',
PFINGSTMONTAG: 'Pfingstmontag',
FRONLEICHNAM: 'Fronleichnam',
MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',
DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',
REFORMATIONSTAG: 'Reformationstag',
ALLERHEILIGEN: 'Allerheiligen',
BUBETAG: 'Buß- und Bettag',
ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',
ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',
WELTKINDERTAG: 'Weltkindertag',
WELTFRAUENTAG: 'Weltfrauentag',
AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',
};
const allHolidays = [
'NEUJAHRSTAG',
'HEILIGEDREIKOENIGE',
'KARFREITAG',
'OSTERSONNTAG',
'OSTERMONTAG',
'TAG_DER_ARBEIT',
'CHRISTIHIMMELFAHRT',
'MARIAHIMMELFAHRT',
'PFINGSTSONNTAG',
'PFINGSTMONTAG',
'FRONLEICHNAM',
'DEUTSCHEEINHEIT',
'REFORMATIONSTAG',
'ALLERHEILIGEN',
'BUBETAG',
'ERSTERWEIHNACHTSFEIERTAG',
'ZWEITERWEIHNACHTSFEIERTAG',
'WELTKINDERTAG',
'WELTFRAUENTAG',
'AUGSBURGER_FRIEDENSFEST',
];
const allRegions = [
'BW',
'BY',
'BE',
'BB',
'HB',
'HE',
'HH',
'MV',
'NI',
'NW',
'RP',
'SL',
'SN',
'ST',
'SH',
'TH',
'BUND',
'AUGSBURG',
'ALL',
];
/*!
* feiertage.js
* @repository https://github.com/sfakir/feiertagejs
* @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md
*
* Copyright 2015-2021 Simon Fakir
* Released under the MIT license
*/
// translations
const defaultLanguage = 'de';
let currentLanguage = defaultLanguage;
const translations = {
de: germanTranslations,
};
/**
* adds a translation for the holidays (e.g. english).
* This also allows to override the German names.
* Hint: Interpolates German for missing translations
* @param {string} isoCode of the new language
* @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg
*/
function addTranslation(isoCode, newTranslation) {
const code = isoCode.toLowerCase();
const defaultTranslation = translations[defaultLanguage];
let missingFields = false;
// fill new Translation with default Language
for (const holiday of allHolidays) {
if (!newTranslation[holiday]) {
missingFields = true;
newTranslation[holiday] = defaultTranslation[holiday];
}
}
if (missingFields) {
console.warn('[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback');
}
translations[code] = newTranslation;
}
/**
* Set a language to default language
* @param {string} isoCode
*/
function setLanguage(isoCode) {
const code = isoCode.toLowerCase();
if (!translations[code]) {
throw new TypeError(`[feiertagejs] tried to set language to ${code} but the translation is missing. Please use addTranslation(isoCode,object) first`);
}
currentLanguage = isoCode;
}
/**
* Get currently set language
* @returns {string}
*/
function getLanguage() {
return currentLanguage;
}
// holidays api
/**
* Checks if a specific date is sunday or holiday.
* @param date
* @param region
* @returns {boolean}
*/
function isSunOrHoliday(date, region) {
checkRegion(region);
return date.getDay() === 0 || isHoliday(date, region);
}
/**
* Check is specific date is holiday.
* @param date
* @param {Region} region two character {@link Region} code
* @returns {boolean}
*/
function isHoliday(date, region) {
checkRegion(region);
const year = date.getFullYear();
const internalDate = toUtcTimestamp(date);
const holidays = getHolidaysAsUtcTimestamps(year, region);
return holidays.indexOf(internalDate) !== -1;
}
function getHolidayByDate(date, region = 'ALL') {
checkRegion(region);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
return holidays.find((holiday) => holiday.equals(date));
}
// additional runtime checks
/**
* Checks if the given region is a valid {@link Region}.
*
* @param region {@link Region} to check
* @throws {Error}
* @private
*/
function checkRegion(region) {
if (region === null || region === undefined) {
throw new Error(`Region must not be undefined or null`);
}
if (allRegions.indexOf(region) === -1) {
throw new Error(`Invalid region: ${region}! Must be one of ${allRegions.toString()}`);
}
}
/**
* Checks if the given holidayName is a valid {@link HolidayType}.
* @param holidayName {@link HolidayType} to check
* @throws {Error}
* @private
*/
function checkHolidayType(holidayName) {
if (holidayName === null || holidayName === undefined) {
throw new TypeError('holidayName must not be null or undefined');
}
if (allHolidays.indexOf(holidayName) === -1) {
throw new Error(`feiertage.js: invalid holiday type "${holidayName}"! Must be one of ${allHolidays.toString()}`);
}
}
function isSpecificHoliday(date, holidayName, region = 'ALL') {
checkRegion(region);
checkHolidayType(holidayName);
const holidays = getHolidaysOfYear(date.getFullYear(), region);
const foundHoliday = holidays.find((holiday) => holiday.equals(date));
if (!foundHoliday) {
return false;
}
return foundHoliday.name === holidayName;
}
/**
* Returns all holidays of a year in a {@link Region}.
* @param year
* @param region
* @returns {Array.<Holiday>}
*/
function getHolidays(year, region) {
let y;
if (typeof year === 'string') {
y = parseInt(year, 10);
}
else {
y = year;
}
checkRegion(region);
return getHolidaysOfYear(y, region);
}
/**
*
* @param {number} year
* @param region
* @returns {number[]}
* @private
*/
function getHolidaysAsUtcTimestamps(year, region) {
const holidays = getHolidaysOfYear(year, region);
return holidays.map((holiday) => toUtcTimestamp(holiday.date));
}
/**
*
* @param {number} year
* @param region
* @returns {{objects: Array.<Holiday>, integers}}
* @private
*/
function getHolidaysOfYear(year, region) {
const easterDate = getEasterDate(year);
const karfreitag = addDays(new Date(easterDate.getTime()), -2);
const ostermontag = addDays(new Date(easterDate.getTime()), 1);
const christiHimmelfahrt = addDays(new Date(easterDate.getTime()), 39);
const pfingstsonntag = addDays(new Date(easterDate.getTime()), 49);
const pfingstmontag = addDays(new Date(easterDate.getTime()), 50);
const holidays = [
...getCommonHolidays(year),
newHoliday('KARFREITAG', karfreitag),
newHoliday('OSTERMONTAG', ostermontag),
newHoliday('CHRISTIHIMMELFAHRT', christiHimmelfahrt),
newHoliday('PFINGSTMONTAG', pfingstmontag),
];
addHeiligeDreiKoenige(year, region, holidays);
addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, holidays);
addFronleichnam(region, easterDate, holidays);
addMariaeHimmelfahrt(year, region, holidays);
addReformationstag(year, region, holidays);
addAllerheiligen(year, region, holidays);
addBussUndBetttag(year, region, holidays);
addWeltkindertag(year, region, holidays);
addWeltfrauenTag(year, region, holidays);
addRegionalHolidays(year, region, holidays);
return holidays.sort((a, b) => a.date.getTime() - b.date.getTime());
}
function getCommonHolidays(year) {
return [
newHoliday('NEUJAHRSTAG', makeDate(year, 1, 1)),
newHoliday('TAG_DER_ARBEIT', makeDate(year, 5, 1)),
newHoliday('DEUTSCHEEINHEIT', makeDate(year, 10, 3)),
newHoliday('ERSTERWEIHNACHTSFEIERTAG', makeDate(year, 12, 25)),
newHoliday('ZWEITERWEIHNACHTSFEIERTAG', makeDate(year, 12, 26)),
];
}
function addRegionalHolidays(year, region, feiertageObjects) {
if (region === 'AUGSBURG') {
feiertageObjects.push(newHoliday('AUGSBURGER_FRIEDENSFEST', makeDate(year, 8, 8)));
}
}
function addHeiligeDreiKoenige(year, region, feiertageObjects) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ST' ||
region === 'ALL') {
feiertageObjects.push(newHoliday('HEILIGEDREIKOENIGE', makeDate(year, 1, 6)));
}
}
function addEasterAndPfingsten(year, region, easterDate, pfingstsonntag, feiertageObjects) {
if (region === 'BB' || region === 'ALL') {
feiertageObjects.push(newHoliday('OSTERSONNTAG', easterDate), newHoliday('PFINGSTSONNTAG', pfingstsonntag));
}
}
function addFronleichnam(region, easterDate, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'HE' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
const fronleichnam = addDays(new Date(easterDate.getTime()), 60);
holidays.push(newHoliday('FRONLEICHNAM', fronleichnam));
}
}
function addMariaeHimmelfahrt(year, region, holidays) {
if (region === 'SL' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'ALL') {
holidays.push(newHoliday('MARIAHIMMELFAHRT', makeDate(year, 8, 15)));
}
}
function addReformationstag(year, region, holidays) {
if (year === 2017 ||
region === 'NI' ||
region === 'BB' ||
region === 'HB' ||
region === 'HH' ||
region === 'MV' ||
region === 'SN' ||
region === 'ST' ||
region === 'TH' ||
region === 'SH' ||
region === 'ALL') {
holidays.push(newHoliday('REFORMATIONSTAG', makeDate(year, 10, 31)));
}
}
function addAllerheiligen(year, region, holidays) {
if (region === 'BW' ||
region === 'BY' ||
region === 'AUGSBURG' ||
region === 'NW' ||
region === 'RP' ||
region === 'SL' ||
region === 'ALL') {
holidays.push(newHoliday('ALLERHEILIGEN', makeDate(year, 11, 1)));
}
}
function addBussUndBetttag(year, region, holidays) {
if (region === 'SN' || region === 'ALL') {
// @todo write test
const bussbettag = getBussBettag(year);
holidays.push(newHoliday('BUBETAG', makeDate(bussbettag.getUTCFullYear(), bussbettag.getUTCMonth() + 1, bussbettag.getUTCDate())));
}
}
function addWeltkindertag(year, region, holidays) {
if (year >= 2019 && (region === 'TH' || region === 'ALL')) {
holidays.push(newHoliday('WELTKINDERTAG', makeDate(year, 9, 20)));
}
}
function addWeltfrauenTag(year, region, feiertageObjects) {
if (year <= 2018) {
return;
}
if (region === 'BE' || region === 'ALL') {
// in Berlin ist der Weltfrauentag ein Feiertag seit 2018
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
if (region === 'MV' && year >= 2023) {
// in MV wird der Weltfrauentag erst ab 2023 eingeführt
feiertageObjects.push(newHoliday('WELTFRAUENTAG', makeDate(year, 3, 8)));
}
}
/**
* Calculates the Easter date of a given year.
* @param year {number}
* @returns {Date} Easter date
* @private
*/
function getEasterDate(year) {
const C = Math.floor(year / 100);
// tslint:disable:binary-expression-operand-order
// tslint generates false positives in the following blocks
const N = year - 19 * Math.floor(year / 19);
const K = Math.floor((C - 17) / 25);
let I = C - Math.floor(C / 4) - Math.floor((C - K) / 3) + 19 * N + 15;
I -= 30 * Math.floor(I / 30);
I -=
Math.floor(I / 28) *
(1 -
Math.floor(I / 28) *
Math.floor(29 / (I + 1)) *
Math.floor((21 - N) / 11));
let J = year + Math.floor(year / 4) + I + 2 - C + Math.floor(C / 4);
J -= 7 * Math.floor(J / 7);
const L = I - J;
const M = 3 + Math.floor((L + 40) / 44);
const D = L + 28 - 31 * Math.floor(M / 4);
// tslint:enable:binary-expression-operand-order
return new Date(year, M - 1, D);
}
/**
* Computes the "Buss- und Bettag"'s date.
* @param jahr {number}
* @returns {Date} the year's "Buss- und Bettag" date
* @private
*/
function getBussBettag(jahr) {
const weihnachten = new Date(jahr, 11, 25, 12, 0, 0);
const ersterAdventOffset = 32;
let wochenTagOffset = weihnachten.getDay() % 7;
if (wochenTagOffset === 0) {
wochenTagOffset = 7;
}
const tageVorWeihnachten = wochenTagOffset + ersterAdventOffset;
let bbtag = new Date(weihnachten.getTime());
bbtag = addDays(bbtag, -tageVorWeihnachten);
return bbtag;
}
/**
* Adds {@code days} days to the given {@link Date}.
* @param date
* @param days
* @returns {Date}
* @private
*/
function addDays(date, days) {
const changedDate = new Date(date);
changedDate.setDate(date.getDate() + days);
return changedDate;
}
/**
* Creates a new {@link Date}.
* @param year
* @param naturalMonth month (1-12)
* @param day
* @returns {Date}
* @private
*/
function makeDate(year, naturalMonth, day) {
return new Date(year, naturalMonth - 1, day);
}
/**
*
* @param name
* @param date
* @returns {Holiday}
* @private
*/
function newHoliday(name, date) {
return {
name,
date,
dateString: localeDateObjectToDateString(date),
trans(lang = currentLanguage) {
console.warn('FeiertageJs: You are using "Holiday.trans() method. This will be replaced in the next major version with translate()"');
return this.translate(lang);
},
translate(lang = currentLanguage) {
return lang === undefined || lang === null
? undefined
: translations[lang][this.name];
},
getNormalizedDate() {
return toUtcTimestamp(this.date);
},
equals(otherDate) {
const dateString = localeDateObjectToDateString(otherDate);
return this.dateString === dateString;
},
};
}
/**
*
* @param date
* @returns {string}
* @private
*/
function localeDateObjectToDateString(date) {
const normalizedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
normalizedDate.setUTCHours(0, 0, 0, 0);
return normalizedDate.toISOString().slice(0, 10);
}
/**
* Returns the UTC timestamp of the given date with hours, minutes, seconds, and milliseconds set to zero.
* @param date
* @returns {number} UTC timestamp
*/
function toUtcTimestamp(date) {
const internalDate = new Date(date);
internalDate.setHours(0, 0, 0, 0);
return internalDate.getTime();
}
exports.addTranslation = addTranslation;
exports.getHolidayByDate = getHolidayByDate;
exports.getHolidays = getHolidays;
exports.getLanguage = getLanguage;
exports.isHoliday = isHoliday;
exports.isSpecificHoliday = isSpecificHoliday;
exports.isSunOrHoliday = isSunOrHoliday;
exports.setLanguage = setLanguage;
}));
//# sourceMappingURL=feiertage.umd.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"feiertage.umd.js","sources":["../src/german-translations.ts","../src/holiday-type.ts","../src/regions.ts","../src/feiertage.ts"],"sourcesContent":["import { TranslationTable } from './feiertage';\n\nexport const germanTranslations: TranslationTable = {\n NEUJAHRSTAG: 'Neujahrstag',\n HEILIGEDREIKOENIGE: 'Heilige Drei Könige',\n KARFREITAG: 'Karfreitag',\n OSTERSONNTAG: 'Ostersonntag',\n OSTERMONTAG: 'Ostermontag',\n TAG_DER_ARBEIT: 'Tag der Arbeit',\n CHRISTIHIMMELFAHRT: 'Christi Himmelfahrt',\n PFINGSTSONNTAG: 'Pfingstsonntag',\n PFINGSTMONTAG: 'Pfingstmontag',\n FRONLEICHNAM: 'Fronleichnam',\n MARIAHIMMELFAHRT: 'Mariä Himmelfahrt',\n DEUTSCHEEINHEIT: 'Tag der Deutschen Einheit',\n REFORMATIONSTAG: 'Reformationstag',\n ALLERHEILIGEN: 'Allerheiligen',\n BUBETAG: 'Buß- und Bettag',\n ERSTERWEIHNACHTSFEIERTAG: '1. Weihnachtstag',\n ZWEITERWEIHNACHTSFEIERTAG: '2. Weihnachtstag',\n WELTKINDERTAG: 'Weltkindertag',\n WELTFRAUENTAG: 'Weltfrauentag',\n AUGSBURGER_FRIEDENSFEST: 'Augsburger Friedensfest',\n};\n","export type HolidayType =\n | 'NEUJAHRSTAG'\n | 'HEILIGEDREIKOENIGE'\n | 'KARFREITAG'\n | 'OSTERSONNTAG'\n | 'OSTERMONTAG'\n | 'TAG_DER_ARBEIT'\n | 'CHRISTIHIMMELFAHRT'\n | 'MARIAHIMMELFAHRT'\n | 'PFINGSTSONNTAG'\n | 'PFINGSTMONTAG'\n | 'FRONLEICHNAM'\n | 'DEUTSCHEEINHEIT'\n | 'REFORMATIONSTAG'\n | 'ALLERHEILIGEN'\n | 'BUBETAG'\n | 'ERSTERWEIHNACHTSFEIERTAG'\n | 'ZWEITERWEIHNACHTSFEIERTAG'\n | 'WELTKINDERTAG'\n | 'WELTFRAUENTAG'\n | 'AUGSBURGER_FRIEDENSFEST';\n\nexport const allHolidays: HolidayType[] = [\n 'NEUJAHRSTAG',\n 'HEILIGEDREIKOENIGE',\n 'KARFREITAG',\n 'OSTERSONNTAG',\n 'OSTERMONTAG',\n 'TAG_DER_ARBEIT',\n 'CHRISTIHIMMELFAHRT',\n 'MARIAHIMMELFAHRT',\n 'PFINGSTSONNTAG',\n 'PFINGSTMONTAG',\n 'FRONLEICHNAM',\n 'DEUTSCHEEINHEIT',\n 'REFORMATIONSTAG',\n 'ALLERHEILIGEN',\n 'BUBETAG',\n 'ERSTERWEIHNACHTSFEIERTAG',\n 'ZWEITERWEIHNACHTSFEIERTAG',\n 'WELTKINDERTAG',\n 'WELTFRAUENTAG',\n 'AUGSBURGER_FRIEDENSFEST',\n];\n","export type Region =\n | 'BW' // Baden-Württemberg\n | 'BY' // Bayern\n | 'BE' // Berlin\n | 'BB' // Brandenburg\n | 'HB' // Bremen\n | 'HE' // Hessen\n | 'HH' // Hamburg\n | 'MV' // Mecklenburg-Vorpommern\n | 'NI' // Niedersachsen\n | 'NW' // Nordrhein-Westfalen\n | 'RP' // Rheinland-Pfalz\n | 'SL' // Saarland\n | 'SN' // Sachsen\n | 'ST' // Sachsen-Anhalt\n | 'SH' // Schleswig-Holstein\n | 'TH' // Thüringen\n | 'BUND' // Gesamt-Deutschland\n // Custom regions with local holidays (incompelte) !\n | 'AUGSBURG'\n | 'ALL';\n\nexport const allRegions: Region[] = [\n 'BW',\n 'BY',\n 'BE',\n 'BB',\n 'HB',\n 'HE',\n 'HH',\n 'MV',\n 'NI',\n 'NW',\n 'RP',\n 'SL',\n 'SN',\n 'ST',\n 'SH',\n 'TH',\n 'BUND',\n 'AUGSBURG',\n 'ALL',\n];\n","/*!\n * feiertage.js\n * @repository https://github.com/sfakir/feiertagejs\n * @docs https://github.com/sfakir/feiertagejs/blob/master/docs.md\n *\n * Copyright 2015-2021 Simon Fakir\n * Released under the MIT license\n */\n\n//\n// Additional readings\n// - how to format a javascript date: http://blog.stevenlevithan.com/archives/date-time-format\n// - the right javascript date: http://stackoverflow.com/questions/10286204/the-right-json-date-format\n//\n\nimport { germanTranslations } from './german-translations';\nimport { Holiday } from './holiday';\nimport { allHolidays, HolidayType } from './holiday-type';\nimport { allRegions, Region } from './regions';\n\n// translations\n\nconst defaultLanguage = 'de';\nlet currentLanguage: string = defaultLanguage;\n\n/**\n * Map of {@link HolidayType} to translation string.\n */\nexport type TranslationTable = { [key in HolidayType]?: string };\n\nconst translations: { [key: string]: TranslationTable } = {\n de: germanTranslations,\n};\n\n/**\n * adds a translation for the holidays (e.g. english).\n * This also allows to override the German names.\n * Hint: Interpolates German for missing translations\n * @param {string} isoCode of the new language\n * @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg\n */\nexport function addTranslation(\n isoCode: string,\n newTranslation: TranslationTable,\n): void {\n const code = isoCode.toLowerCase();\n const defaultTranslation = translations[defaultLanguage];\n let missingFields = false;\n\n // fill new Translation with default Language\n for (const holiday of allHolidays) {\n if (!newTranslation[holiday]) {\n missingFields = true;\n newTranslation[holiday] = defaultTranslation[holiday];\n }\n }\n if (missingFields) {\n console.warn(\n '[feiertagejs] addTranslation: you did not add all holidays in your translation! Took German as fallback',\n );\n }\n\n translations[code] = newTranslation;\n}\n\n/**\n * Set a language to default language\n * @param {string} isoCode\n */\nexport function setLanguage(isoCode: string): void {\n const code = isoCode.toLowerCase();\n if (!translations[code])Line truncated
+144
View File
@@ -0,0 +1,144 @@
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### Table of Contents
*Types*
- [HolidayType](#holidaytype)
- [Region](#region)
- [Holiday](#holiday)
- [allHolidays](#allholidays)
- [allRegions](#allregions)
- [TranslationTable](#translationtable)
*API*
- [isHoliday(date, region)](#isholiday)
- [getHolidayByDate(date, region)](#getholidaybydate)
- [getHolidays(year, region)](#getholidays)
- [isSunOrHoliday(date, region)](#issunorholiday)
- [isSpecificHoliday(date, name, region)](#isspecificholiday)
- [addTranslation(isoCode, translation)](#addtranslation)
- [setLanguage(lng)](#setlanguage)
- [getLanguage()](#getlanguage)
## Types
### HolidayType
Type: (`"NEUJAHRSTAG"` \| `"HEILIGEDREIKOENIGE"` \| `"KARFREITAG"` \| `"OSTERSONNTAG"` \| `"OSTERMONTAG"` \| `"TAG_DER_ARBEIT"` \| `"CHRISTIHIMMELFAHRT"` \| `"MARIAHIMMELFAHRT"` \| `"PFINGSTSONNTAG"` \| `"PFINGSTMONTAG"` \| `"FRONLEICHNAM"` \| `"DEUTSCHEEINHEIT"` \| `"REFORMATIONSTAG"` \| `"ALLERHEILIGEN"` \| `"BUBETAG"` \| `"ERSTERWEIHNACHTSFEIERTAG"` \| `"ZWEITERWEIHNACHTSFEIERTAG"` \| `"WELTKINDERTAG"` \| `"WELTFRAUENTAG"` \| `"AUGSBURGER_FRIEDENSFEST"`)
### Region
Type: (`"BW"` \| `"BY"` \| `"BE"` \| `"BB"` \| `"HB"` \| `"HE"` \| `"HH"` \| `"MV"` \| `"NI"` \| `"NW"` \| `"RP"` \| `"SL"` \| `"SN"` \| `"ST"` \| `"SH"` \| `"TH"` \| `"BUND"` \| `"ALL"`)
As defined here: https://de.wikipedia.org/wiki/Land_(Deutschland)#Amtliche_bzw._Eigenbezeichnungen
The difference between BUND and ALL is defined as follows:
* "ALL" refers to every holiday which is valid in **at least** one region. So a holiday that only applies to one state will be included.
* "BUND" refers to holidays that are valid in every region ("bundesweit"). So a holiday that only applies to one state will not be included.
### Holiday
Type: {name: [HolidayType](#holidaytype), date: [Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date), trans: function (lang: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?): [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), dateString: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), equals: function (date: [Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)): [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)}
**Properties**
- `name` **[HolidayType](#holidaytype)**
- `date` **[Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)**
- `trans` **function (lang: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?): [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `dateString` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `equals` **function (date: [Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)): [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
### allHolidays
Type: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[HolidayType](#holidaytype)>
### allRegions
Type: [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[Region](#region)>
### TranslationTable
Map of [HolidayType](#holidaytype) to translation string.
Type: {}
## API
### addTranslation()
Adds a translation for the holidays (e.g. English).
This also allows overriding the German names.
Hint: Interpolates German for missing translations
**Parameters**
- `isoCode` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** of the new language
- `newTranslation` **[TranslationTable](#translationtable)** map of {HolidayType} to translation stringg
### setLanguage()
Set a language to default language
**Parameters**
- `isoCode` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
### getLanguage()
Get currently set language
Returns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)**
### isSunOrHoliday()
Checks if a specific date is sunday or holiday.
**Parameters**
- `date` **[Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)**
- `region` **[Region](#region)**
Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
### isHoliday()
Check is specific date is holiday.
**Parameters**
- `date` **[Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)**
- `region` **[Region](#region)** two character [Region](#region) code
Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
### getHolidayByDate()
**Parameters**
- `date` **[Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)**
- `region` **[Region](#region)** (optional, default `'ALL'`)
Returns **([Holiday](#holiday) | void)**
### isSpecificHoliday()
**Parameters**
- `date` **[Date](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date)**
- `holidayName` **[HolidayType](#holidaytype)**
- `region` **[Region](#region)** (optional, default `'ALL'`)
Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
### getHolidays()
Returns all holidays of a year in a [Region](#region).
**Parameters**
- `year` **([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))**
- `region` **[Region](#region)**
Returns **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[Holiday](#holiday)>**
+113
View File
@@ -0,0 +1,113 @@
declare type Region =
| 'BW' // Baden-Württemberg
| 'BY' // Bayern
| 'BE' // Berlin
| 'BB' // Brandenburg
| 'HB' // Bremen
| 'HE' // Hessen
| 'HH' // Hamburg
| 'MV' // Mecklenburg-Vorpommern
| 'NI' // Niedersachsen
| 'NW' // Nordrhein-Westfalen
| 'RP' // Rheinland-Pfalz
| 'SL' // Saarland
| 'SN' // Sachsen
| 'ST' // Sachsen-Anhalt
| 'SH' // Schleswig-Holstein
| 'TH' // Thüringen
| 'BUND' // Gesamt-Deutschland
| 'AUGSBURG'
| 'ALL';
declare type Holiday = {
name: HolidayType;
date: Date;
trans?: (lang: string | undefined) => string; // deprecated;
translate: (lang?: string | undefined) => string;
dateString: string;
equals: (date: Date) => boolean;
};
declare type HolidayType =
| 'NEUJAHRSTAG'
| 'HEILIGEDREIKOENIGE'
| 'KARFREITAG'
| 'OSTERSONNTAG'
| 'OSTERMONTAG'
| 'TAG_DER_ARBEIT'
| 'CHRISTIHIMMELFAHRT'
| 'MARIAHIMMELFAHRT'
| 'PFINGSTSONNTAG'
| 'PFINGSTMONTAG'
| 'FRONLEICHNAM'
| 'DEUTSCHEEINHEIT'
| 'REFORMATIONSTAG'
| 'ALLERHEILIGEN'
| 'BUBETAG'
| 'ERSTERWEIHNACHTSFEIERTAG'
| 'ZWEITERWEIHNACHTSFEIERTAG';
/**
* Map of {@link HolidayType} to translation string.
*/
export type TranslationTable = {
[key: string]: string;
};
/**
* adds a translation for the holidays (e.g. english).
* This also allows to override the German names.
* Hint: Interpolates German for missing translations
* @param {string} isoCode of the new language
* @param {TranslationTable} newTranslation map of {HolidayType} to translation stringg
*/
declare function addTranslation(
isoCode: string,
newTranslation: TranslationTable,
): void;
/**
* Set a language to default language
* @param {string} isoCode
*/
declare function setLanguage(isoCode: string): void;
/**
* Get currently set language
* @returns {string}
*/
declare function getLanguage(): string;
// holidays api
/**
* Checks if a specific date is sunday or holiday.
* @param date
* @param region
* @returns {boolean}
*/
declare function isSunOrHoliday(date: Date, region: Region): boolean;
/**
* Check is specific date is holiday.
* @param date
* @param {Region} region two character {@link Region} code
* @returns {boolean}
*/
declare function isHoliday(date: Date, region: Region): boolean;
declare function getHolidayByDate(date: Date, region: Region): Holiday | void;
declare function isSpecificHoliday(
date: Date,
holidayName: HolidayType,
region: Region,
): boolean;
/**
* Returns all holidays of a year in a {@link Region}.
* @param year
* @param region
* @returns {Array.<Holiday>}
*/
declare function getHolidays(year: number | string, region: Region): Holiday[];
+53
View File
@@ -0,0 +1,53 @@
{
"name": "feiertagejs",
"version": "1.3.9",
"description": "A module to calculate German holidays made for node.js",
"type": "module",
"main": "build/feiertage.umd.cjs",
"module": "build/feiertage.js",
"types": "index.d.ts",
"scripts": {
"test": "vitest run --coverage",
"test:w": "vitest watch",
"format": "prettier --write \"{**/*,*}.{ts,json}\" \"!coverage/**\" \"!build/**\" \"!package.json\" \"!package-lock.json\" --cache",
"lint": "eslint \"src\" \"spec\"",
"build": "rollup -c"
},
"repository": {
"type": "git",
"url": "https://github.com/sfakir/feiertagejs"
},
"keywords": [
"node",
"holidays",
"feiertage",
"javascript"
],
"engines": {
"node": ">=8.0.0"
},
"author": "Simon Fakir",
"license": "MIT",
"bugs": {
"url": "https://github.com/sfakir/feiertagejs/issues"
},
"homepage": "https://github.com/sfakir/feiertagejs",
"devDependencies": {
"@vitest/coverage-c8": "^0.26.2",
"prettier": "^2.8.1",
"rollup": "^3.9.0",
"@rollup/plugin-typescript": "^10.0.1",
"typescript": "^4.9.4",
"vitest": "^0.26.2",
"@typescript-eslint/eslint-plugin": "^5.47.1",
"@typescript-eslint/parser": "^5.47.1",
"eslint": "^8.30.0",
"eslint-config-prettier": "^8.5.0"
},
"files": [
"build",
"docs.md",
"Readme.md",
"index.d.ts"
]
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "TIF22A_AnwProjekt_B",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"feiertagejs": "^1.3.9"
}
},
"node_modules/feiertagejs": {
"version": "1.3.9",
"resolved": "https://registry.npmjs.org/feiertagejs/-/feiertagejs-1.3.9.tgz",
"integrity": "sha512-tUP+WBv2OWBhPwe3NfqwCtjMq+ym598a42tfqmL0FySswEb9xs96p2iKwqqx+lxKieu1njJBRZKsFm92bJhxZw==",
"engines": {
"node": ">=8.0.0"
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"dependencies": {
"feiertagejs": "^1.3.9"
}
}