V^-F_kqTu&F(?a4N? zZgL90HNwMy?+GXuLfh8TB3V~MkaM3M;0bZ;d*l!&_pdH;^qx1*S1`$Y)h+wo%rw3$ zVRi_Qy>cVYQWMr5`IWF$d1ay4{7ZN1U6Pa!emwhFlclC+9}#!(cl2l=pWn1BMtMx-D( za 6Wg9idy;uXB6A_yE%o!R?|XKI z$;~-(szFH^HF`0lBEmVnkw6$ccb>1wGNH|G6QJQL~bvmg(K_F}!59iiNm5Gu^^^;s}Ex%Zz zkQ5wF!DAUwUzYKk0sws;8!f|114Z;k%1V+_=F%7?IrLR>K!t1gV0f0~peJx<7rb6#psp+B3!hS97SI+h|k20yWfW}fxTKlf--F$VX7fanc16Bb0wYAzZ zc%bj lgfye^OfYO38||vID36udt$(Lc{CE zU*u1qVOEtFTXxSYJzG(j|J2) q8Cyrb;(0(0%fpsa2MXh$AflpZ*TcX>&)T{pPh$&HP`3%L7;5wf|*I>mV zoEDJnLUWrg!%$Vr);+D4tU0;YwBs6nTmd3-Y;UC%u@0edie)e0u!{6F4(hAyWF(5h zBT0lE)xhZE&~ZxL7PNb9@&~ttg`Wx&&TU>7bJEfI*8M4pWO|jE?=q5i(ij(BXiH#e zB+)!-^tFjw&(peE^;+P9m5l_yfRKE4hwql2(mqL(P`%K zFh9|K&D{|O3t5p&%zFd7RVW{!kpIMU4U@}y=%|n>*q#nEOO-f0*UB0*@9^g{bdrtM z107|bRXbZ*Y+RzHNA&YCwEVLvc$>_ng7#%D%O1_;r6!_AKu1{g*0~(@l%`qswDT`n zk8zCC0KuJWfPYQN#LKnve0$u#Uu15nd@K$^Ex_B7By&qkUG% JQ}S&&n~FEsFpd%Xf?ZWk=lwXZlI^p8$hZkC5u}khP*xEQ z(kd)_N#=Wupt^bZQvML~u21W9#)&fOZ^N++pTIG
nI}$@UZ!cPJw>opKnIMxEM?KAb;IoGJOaPX^Jt!m9E12G|eb~Bktb6f6bp|bA zhus&v=zwTw-iy2W8i=jcC?5%eh!D$2+~vwr!o#T6{~6t_oxWCVP+3G%I-g-o|KfZq zVIC67RGIViiZWCS*5MoY8`S5FORC}PZX=(@Vireb4*xo^Aj1rPGRlOa3S8U~KaC%_ zU)#j2h^F&`n4>cb>t*4To1 W@lk=KbP_Z<=Zfj| z+y}jgnt>H68O(s@KO3EkZq!&r#X8DFU2RLu9mr(9P*(I6OyeBXF?rGh4eh$B!^ULg zM>`V>Tv5;if2AK#Ux$vi#}nZ}dGSs%UF4wEBc)}mgGDJ5a8pcnTnIO?u=eZMYKRSM z(dC7$Wrub{sB1x)S$6yr>fNvJp`&}}W*Y=wKTi@!rV9PZyApT@&99l> zo~Wj#h65|tdx5rWTp=E<{$pxz4OFw$-#{aX%<+VgxWsH4YODti<_$(f?Cu;VVoBse zI+$<)2x}rNywImElo;rN!kRn>Z=TFH-WrfZe{xfJ$RNXz^?7c}mYZ9^RSR;VWO!Je zmAGoWtqEZcnEB(s9FW`QKW1>m))n{b;d}7K=-a+5%@O0P#;Z0V>>LdJXI2Q9qf~=B z_KKUVit@C@d9AnL`T7l^3r@R^fcSCFC$6|l9XV7727w kLqHJJ)&^ML;cX$R^F literal 0 HcmV?d00001 diff --git a/src/main/resources/config/liquibase/fake-data/blob/hipster.txt b/src/main/resources/config/liquibase/fake-data/blob/hipster.txt new file mode 100644 index 0000000..3bf9d1e --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/blob/hipster.txt @@ -0,0 +1 @@ +JHipster is a development platform to generate, develop and deploy Spring Boot + Angular / React / Vue Web applications and Spring microservices. \ No newline at end of file diff --git a/src/main/resources/config/liquibase/fake-data/code_tables.csv b/src/main/resources/config/liquibase/fake-data/code_tables.csv new file mode 100644 index 0000000..479d1e5 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/code_tables.csv @@ -0,0 +1,11 @@ +id;category;code_key;code_value;created_by;created_date;last_modified_by;last_modified_date +1;if;for cleverly;eek putrid;breeze;2024-08-24T15:43:24;gosh;2024-08-24T21:55:03 +2;hourly;that intent;hm well-off;hold distinguish however;2024-08-24T16:57:46;exorcise stealthily;2024-08-25T03:55:47 +3;heed where;mouth claw;among;klap;2024-08-24T20:02:11;as tart spirited;2024-08-25T03:16:56 +4;count;with aha during;phooey;promotion;2024-08-25T03:24:15;joyously;2024-08-24T18:26:13 +5;yum;blather;as apropos;righteously healthily gas;2024-08-24T21:59:54;onto troubled normal;2024-08-25T08:02:16 +6;considering quarrelsomely;woot fruitful;repress;happy;2024-08-25T07:18:04;length seemingly passing;2024-08-24T12:49:57 +7;geez whenever;while;cayenne successfully;rough;2024-08-24T17:36:46;gadzooks coaxingly;2024-08-24T21:52:44 +8;gosh thrifty bijou;phooey care aw;even lob yearly;knock pfft;2024-08-24T17:41:43;out port;2024-08-24T18:02:59 +9;boldly another than;unless;slosh computer even;coolly stiff whoever;2024-08-24T13:36:47;including scaly bare;2024-08-25T02:54:04 +10;hm;pooh;yearly gainsay;sensor feline;2024-08-25T04:38:44;greedily zowie gosh;2024-08-24T21:09:31 diff --git a/src/main/resources/config/liquibase/fake-data/message.csv b/src/main/resources/config/liquibase/fake-data/message.csv new file mode 100644 index 0000000..15b40e2 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/message.csv @@ -0,0 +1,11 @@ +id;content;sent_at;is_deleted;created_by;created_date;last_modified_by;last_modified_date +1;../fake-data/blob/hipster.txt;2024-08-24T19:05:04;true;angrily amidst small;2024-08-24T09:00:16;wisely;2024-08-24T19:11:45 +2;../fake-data/blob/hipster.txt;2024-08-24T15:38:44;false;atop deny;2024-08-24T11:55:15;agitated unfortunately;2024-08-25T00:40:49 +3;../fake-data/blob/hipster.txt;2024-08-25T00:29:51;false;zowie;2024-08-25T01:54:42;ensconce yieldingly encourage;2024-08-25T03:13:20 +4;../fake-data/blob/hipster.txt;2024-08-24T13:40:46;false;feisty lest odd;2024-08-24T17:44:05;catalyse loose nor;2024-08-24T20:51:11 +5;../fake-data/blob/hipster.txt;2024-08-24T09:35:08;true;gadzooks athwart ugh;2024-08-24T10:16:08;annual kite;2024-08-25T06:41:34 +6;../fake-data/blob/hipster.txt;2024-08-24T16:49:58;true;during frightfully;2024-08-25T04:38:14;experience;2024-08-25T08:25:53 +7;../fake-data/blob/hipster.txt;2024-08-25T06:55:11;false;perfumed;2024-08-25T07:24:15;until meanwhile publicity;2024-08-24T13:09:02 +8;../fake-data/blob/hipster.txt;2024-08-25T00:11:23;false;well procurement easy;2024-08-24T09:09:29;psst as fooey;2024-08-25T04:12:28 +9;../fake-data/blob/hipster.txt;2024-08-24T10:03:51;true;useful;2024-08-24T12:11:15;consequently;2024-08-24T16:03:21 +10;../fake-data/blob/hipster.txt;2024-08-24T09:02:38;false;drag hence;2024-08-24T13:34:49;dribble er;2024-08-24T19:45:44 diff --git a/src/main/resources/config/liquibase/fake-data/notification.csv b/src/main/resources/config/liquibase/fake-data/notification.csv new file mode 100644 index 0000000..6968054 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/notification.csv @@ -0,0 +1,11 @@ +id;notification_ref_id;content;is_read;created_by;created_date;last_modified_by;last_modified_date +1;11369be3-2766-4089-9fd0-f2ad74906479;../fake-data/blob/hipster.txt;true;qua;2024-08-24T17:41:10;superb whereas fantastic;2024-08-24T14:53:29 +2;23c15533-1641-432c-ac9a-fa7f776e8024;../fake-data/blob/hipster.txt;false;patronise;2024-08-24T17:35:46;yippee;2024-08-25T07:52:57 +3;0f39abf6-3b06-4c27-9364-54875d67acfa;../fake-data/blob/hipster.txt;false;sedately shuttle epic;2024-08-24T15:49:05;popular;2024-08-24T19:17:35 +4;5dc86e65-22be-45f9-ac28-f8144d814f04;../fake-data/blob/hipster.txt;true;critical;2024-08-24T11:35:09;indeed per;2024-08-25T05:45:34 +5;b21a16c3-f885-4925-b0fe-5df1d322aef8;../fake-data/blob/hipster.txt;false;whoever;2024-08-25T00:35:19;hard enormously during;2024-08-25T00:20:46 +6;b3f54889-3828-49c3-ab11-1016b911b754;../fake-data/blob/hipster.txt;false;text who beside;2024-08-24T12:41:39;until meh;2024-08-24T17:57:18 +7;780453dd-3d7f-463f-ab05-f840ad2c8846;../fake-data/blob/hipster.txt;false;offence burglarize quicker;2024-08-25T07:47:02;between;2024-08-24T14:19:15 +8;aba3b916-1393-4170-ad4f-fa0b91826a60;../fake-data/blob/hipster.txt;false;about;2024-08-24T14:08:09;capitalise annually;2024-08-24T15:42:15 +9;d725d05a-614d-4a44-b9af-7bd60bcaef0b;../fake-data/blob/hipster.txt;false;boo aha um;2024-08-24T19:36:12;ouch admired courageously;2024-08-25T05:56:00 +10;3b391336-8682-4c3a-af64-b783616d591c;../fake-data/blob/hipster.txt;true;accomplishment with hm;2024-08-24T10:55:22;lest;2024-08-24T16:12:00 diff --git a/src/main/resources/config/liquibase/fake-data/skill.csv b/src/main/resources/config/liquibase/fake-data/skill.csv new file mode 100644 index 0000000..83e3d15 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/skill.csv @@ -0,0 +1,11 @@ +id;skill_name;individual_skill_desc;years_of_exp;created_by;created_date;last_modified_by;last_modified_date +1;pasta;woot who;25847;legume ruffle provided;2024-08-25T05:58:26;loftily;2024-08-25T04:28:13 +2;concerning;meh;4747;often imaginative;2024-08-24T12:50:12;mountainous brr brutalize;2024-08-25T02:28:17 +3;waken treasure disloyal;what toward nippy;7032;as;2024-08-25T04:55:08;expansionism ant;2024-08-24T12:17:38 +4;insidious;frayed;9578;gracefully likewise;2024-08-25T05:34:58;gee zesty;2024-08-24T13:42:23 +5;pug drat;and bah;21753;oh;2024-08-24T16:37:02;limply yippee;2024-08-25T07:33:54 +6;considering keenly;instead smoothly;13995;mmm inquisitively ready;2024-08-24T12:33:41;gee enthusiastically;2024-08-25T06:31:02 +7;nor;wavy;22757;sweetly psst upright;2024-08-25T06:42:24;flanker;2024-08-25T01:55:09 +8;keenly nest;reamer;32127;svelte;2024-08-25T07:17:10;bubbly idolized especially;2024-08-24T22:10:59 +9;cavernous below;atop under cooperative;16047;smooth oof angrily;2024-08-25T02:05:33;rationale grumpy vibrate;2024-08-24T19:06:03 +10;unto;an;23772;interpretation zing;2024-08-24T09:43:21;flippant foreclose total;2024-08-24T12:28:19 diff --git a/src/main/resources/config/liquibase/fake-data/user_profile.csv b/src/main/resources/config/liquibase/fake-data/user_profile.csv new file mode 100644 index 0000000..5c35f87 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/user_profile.csv @@ -0,0 +1,3 @@ +id;nickname;job_role;about_me;profile_picture;created_by;created_date;last_modified_by;last_modified_date;user_id +1;french necessary uh-huh;pfft;queasily rigidly never;mmm around;what;2024-08-24T15:56:27;playfully;2024-08-25T07:58:16;1 +2;excellent;bah reprimand until;oof fully;elbow;whirlwind snitch hang;2024-08-24T09:11:07;zowie go-kart;2024-08-24T22:35:39;2 diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index 4b29518..ceccd92 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -17,7 +17,21 @@ + + + + + + + + + + + + + + diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite-delete-dialog.tsx b/src/main/webapp/app/entities/activity-invite/activity-invite-delete-dialog.tsx new file mode 100644 index 0000000..d375de0 --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite-delete-dialog.tsx @@ -0,0 +1,64 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './activity-invite.reducer'; + +export const ActivityInviteDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const activityInviteEntity = useAppSelector(state => state.activityInvite.entity); + const updateSuccess = useAppSelector(state => state.activityInvite.updateSuccess); + + const handleClose = () => { + navigate('/activity-invite'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(activityInviteEntity.id)); + }; + + return ( + + + ); +}; + +export default ActivityInviteDeleteDialog; diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite-detail.tsx b/src/main/webapp/app/entities/activity-invite/activity-invite-detail.tsx new file mode 100644 index 0000000..f2b8a00 --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite-detail.tsx @@ -0,0 +1,78 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './activity-invite.reducer'; + +export const ActivityInviteDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const activityInviteEntity = useAppSelector(state => state.activityInvite.entity); + return ( ++ Confirm delete operation + ++ Are you sure you want to delete Activity Invite {activityInviteEntity.id}? + ++ + + ++
+ ); +}; + +export default ActivityInviteDetail; diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite-reducer.spec.ts b/src/main/webapp/app/entities/activity-invite/activity-invite-reducer.spec.ts new file mode 100644 index 0000000..028df35 --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite-reducer.spec.ts @@ -0,0 +1,265 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { IActivityInvite, defaultValue } from 'app/shared/model/activity-invite.model'; +import reducer, { + createEntity, + deleteEntity, + getEntities, + getEntity, + updateEntity, + partialUpdateEntity, + reset, +} from './activity-invite.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Activity Invite
++
+ + + + +- + ID +
+- {activityInviteEntity.id}
+- + Will Participate +
+- {activityInviteEntity.willParticipate ? 'true' : 'false'}
+- + Created By +
+- {activityInviteEntity.createdBy}
+- + Created Date +
+- + {activityInviteEntity.createdDate ? ( +
++ ) : null} + - + Last Modified By +
+- {activityInviteEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {activityInviteEntity.lastModifiedDate ? ( +
++ ) : null} + - Activity
+- {activityInviteEntity.activity ? activityInviteEntity.activity.id : ''}
+- Invitee Profile
+- {activityInviteEntity.inviteeProfile ? activityInviteEntity.inviteeProfile.id : ''}
+- Status
+- {activityInviteEntity.status ? activityInviteEntity.status.id : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_ACTIVITYINVITE_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_ACTIVITYINVITE actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_ACTIVITYINVITE actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_ACTIVITYINVITE actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_ACTIVITYINVITE actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_ACTIVITYINVITE actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite-update.tsx b/src/main/webapp/app/entities/activity-invite/activity-invite-update.tsx new file mode 100644 index 0000000..a0c0340 --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite-update.tsx @@ -0,0 +1,198 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IActivity } from 'app/shared/model/activity.model'; +import { getEntities as getActivities } from 'app/entities/activity/activity.reducer'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntities as getUserProfiles } from 'app/entities/user-profile/user-profile.reducer'; +import { ICodeTables } from 'app/shared/model/code-tables.model'; +import { getEntities as getCodeTables } from 'app/entities/code-tables/code-tables.reducer'; +import { IActivityInvite } from 'app/shared/model/activity-invite.model'; +import { getEntity, updateEntity, createEntity, reset } from './activity-invite.reducer'; + +export const ActivityInviteUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const activities = useAppSelector(state => state.activity.entities); + const userProfiles = useAppSelector(state => state.userProfile.entities); + const codeTables = useAppSelector(state => state.codeTables.entities); + const activityInviteEntity = useAppSelector(state => state.activityInvite.entity); + const loading = useAppSelector(state => state.activityInvite.loading); + const updating = useAppSelector(state => state.activityInvite.updating); + const updateSuccess = useAppSelector(state => state.activityInvite.updateSuccess); + + const handleClose = () => { + navigate('/activity-invite'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getActivities({})); + dispatch(getUserProfiles({})); + dispatch(getCodeTables({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...activityInviteEntity, + ...values, + activity: activities.find(it => it.id.toString() === values.activity?.toString()), + inviteeProfile: userProfiles.find(it => it.id.toString() === values.inviteeProfile?.toString()), + status: codeTables.find(it => it.id.toString() === values.status?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...activityInviteEntity, + createdDate: convertDateTimeFromServer(activityInviteEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(activityInviteEntity.lastModifiedDate), + activity: activityInviteEntity?.activity?.id, + inviteeProfile: activityInviteEntity?.inviteeProfile?.id, + status: activityInviteEntity?.status?.id, + }; + + return ( + ++ ); +}; + +export default ActivityInviteUpdate; diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite.reducer.ts b/src/main/webapp/app/entities/activity-invite/activity-invite.reducer.ts new file mode 100644 index 0000000..952145e --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { IActivityInvite, defaultValue } from 'app/shared/model/activity-invite.model'; + +const initialState: EntityState+
++ + Create or edit a Activity Invite +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? ( + + )} + ++ ) : null} + + + + + + + + {activities + ? activities.map(otherEntity => ( + + )) + : null} + ++ + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + ++ + {codeTables + ? codeTables.map(otherEntity => ( + + )) + : null} + + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/activity-invites'; + +// Actions + +export const getEntities = createAsyncThunk( + 'activityInvite/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'activityInvite/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'activityInvite/create_entity', + async (entity: IActivityInvite, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'activityInvite/update_entity', + async (entity: IActivityInvite, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'activityInvite/partial_update_entity', + async (entity: IActivityInvite, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'activityInvite/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const ActivityInviteSlice = createEntitySlice({ + name: 'activityInvite', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = ActivityInviteSlice.actions; + +// Reducer +export default ActivityInviteSlice.reducer; diff --git a/src/main/webapp/app/entities/activity-invite/activity-invite.tsx b/src/main/webapp/app/entities/activity-invite/activity-invite.tsx new file mode 100644 index 0000000..174f9aa --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/activity-invite.tsx @@ -0,0 +1,240 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './activity-invite.reducer'; + +export const ActivityInvite = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const activityInviteList = useAppSelector(state => state.activityInvite.entities); + const loading = useAppSelector(state => state.activityInvite.loading); + const links = useAppSelector(state => state.activityInvite.links); + const updateSuccess = useAppSelector(state => state.activityInvite.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default ActivityInvite; diff --git a/src/main/webapp/app/entities/activity-invite/index.tsx b/src/main/webapp/app/entities/activity-invite/index.tsx new file mode 100644 index 0000000..d50a3d8 --- /dev/null +++ b/src/main/webapp/app/entities/activity-invite/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import ActivityInvite from './activity-invite'; +import ActivityInviteDetail from './activity-invite-detail'; +import ActivityInviteUpdate from './activity-invite-update'; +import ActivityInviteDeleteDialog from './activity-invite-delete-dialog'; + +const ActivityInviteRoutes = () => ( ++ Activity Invites +
++ + +++ Create a new Activity Invite + + +} + > + {activityInviteList && activityInviteList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {activityInviteList.map((activityInvite, i) => ( ++ ID ++ + Will Participate ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + Activity ++ + Invitee Profile ++ + Status ++ + + + ))} + ++ + +{activityInvite.willParticipate ? 'true' : 'false'} +{activityInvite.createdBy} ++ {activityInvite.createdDate ? ( + ++ ) : null} + {activityInvite.lastModifiedBy} ++ {activityInvite.lastModifiedDate ? ( + ++ ) : null} + + {activityInvite.activity ? ( + {activityInvite.activity.id} + ) : ( + '' + )} + ++ {activityInvite.inviteeProfile ? ( + {activityInvite.inviteeProfile.id} + ) : ( + '' + )} + ++ {activityInvite.status ? {activityInvite.status.id} : ''} + ++ ++ + + ++No Activity Invites found+ )} + ++ +); + +export default ActivityInviteRoutes; diff --git a/src/main/webapp/app/entities/activity/activity-delete-dialog.tsx b/src/main/webapp/app/entities/activity/activity-delete-dialog.tsx new file mode 100644 index 0000000..2042a33 --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity-delete-dialog.tsx @@ -0,0 +1,62 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './activity.reducer'; + +export const ActivityDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const activityEntity = useAppSelector(state => state.activity.entity); + const updateSuccess = useAppSelector(state => state.activity.updateSuccess); + + const handleClose = () => { + navigate('/activity'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(activityEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default ActivityDeleteDialog; diff --git a/src/main/webapp/app/entities/activity/activity-detail.tsx b/src/main/webapp/app/entities/activity/activity-detail.tsx new file mode 100644 index 0000000..4200e0b --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity-detail.tsx @@ -0,0 +1,88 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { byteSize, TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './activity.reducer'; + +export const ActivityDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const activityEntity = useAppSelector(state => state.activity.entity); + return ( ++ Confirm delete operation + +Are you sure you want to delete Activity {activityEntity.id}? ++ + + ++
+ ); +}; + +export default ActivityDetail; diff --git a/src/main/webapp/app/entities/activity/activity-reducer.spec.ts b/src/main/webapp/app/entities/activity/activity-reducer.spec.ts new file mode 100644 index 0000000..3ec82fa --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity-reducer.spec.ts @@ -0,0 +1,257 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { IActivity, defaultValue } from 'app/shared/model/activity.model'; +import reducer, { createEntity, deleteEntity, getEntities, getEntity, updateEntity, partialUpdateEntity, reset } from './activity.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Activity
++
+ + + + +- + ID +
+- {activityEntity.id}
+- + Activity Time +
+- + {activityEntity.activityTime ?
+: null} + - + Duration +
+- {activityEntity.duration}
+- + Venue +
+- {activityEntity.venue}
+- + Details +
+- {activityEntity.details}
+- + Created By +
+- {activityEntity.createdBy}
+- + Created Date +
+- + {activityEntity.createdDate ?
+: null} + - + Last Modified By +
+- {activityEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {activityEntity.lastModifiedDate ? ( +
++ ) : null} + - Creator Profile
+- {activityEntity.creatorProfile ? activityEntity.creatorProfile.id : ''}
+- Skill
+- {activityEntity.skill ? activityEntity.skill.id : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_ACTIVITY_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_ACTIVITY actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_ACTIVITY actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_ACTIVITY actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_ACTIVITY actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_ACTIVITY actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/activity/activity-update.tsx b/src/main/webapp/app/entities/activity/activity-update.tsx new file mode 100644 index 0000000..2c705e8 --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity-update.tsx @@ -0,0 +1,201 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntities as getUserProfiles } from 'app/entities/user-profile/user-profile.reducer'; +import { ISkill } from 'app/shared/model/skill.model'; +import { getEntities as getSkills } from 'app/entities/skill/skill.reducer'; +import { IActivity } from 'app/shared/model/activity.model'; +import { getEntity, updateEntity, createEntity, reset } from './activity.reducer'; + +export const ActivityUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const userProfiles = useAppSelector(state => state.userProfile.entities); + const skills = useAppSelector(state => state.skill.entities); + const activityEntity = useAppSelector(state => state.activity.entity); + const loading = useAppSelector(state => state.activity.loading); + const updating = useAppSelector(state => state.activity.updating); + const updateSuccess = useAppSelector(state => state.activity.updateSuccess); + + const handleClose = () => { + navigate('/activity'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getUserProfiles({})); + dispatch(getSkills({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.activityTime = convertDateTimeToServer(values.activityTime); + if (values.duration !== undefined && typeof values.duration !== 'number') { + values.duration = Number(values.duration); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...activityEntity, + ...values, + creatorProfile: userProfiles.find(it => it.id.toString() === values.creatorProfile?.toString()), + skill: skills.find(it => it.id.toString() === values.skill?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + activityTime: displayDefaultDateTime(), + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...activityEntity, + activityTime: convertDateTimeFromServer(activityEntity.activityTime), + createdDate: convertDateTimeFromServer(activityEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(activityEntity.lastModifiedDate), + creatorProfile: activityEntity?.creatorProfile?.id, + skill: activityEntity?.skill?.id, + }; + + return ( + ++ ); +}; + +export default ActivityUpdate; diff --git a/src/main/webapp/app/entities/activity/activity.reducer.ts b/src/main/webapp/app/entities/activity/activity.reducer.ts new file mode 100644 index 0000000..04e2b28 --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { IActivity, defaultValue } from 'app/shared/model/activity.model'; + +const initialState: EntityState+
++ + Create or edit a Activity +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + + + + + + + + + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + ++ + {skills + ? skills.map(otherEntity => ( + + )) + : null} + + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/activities'; + +// Actions + +export const getEntities = createAsyncThunk( + 'activity/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'activity/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'activity/create_entity', + async (entity: IActivity, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'activity/update_entity', + async (entity: IActivity, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'activity/partial_update_entity', + async (entity: IActivity, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'activity/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const ActivitySlice = createEntitySlice({ + name: 'activity', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = ActivitySlice.actions; + +// Reducer +export default ActivitySlice.reducer; diff --git a/src/main/webapp/app/entities/activity/activity.tsx b/src/main/webapp/app/entities/activity/activity.tsx new file mode 100644 index 0000000..6a3189a --- /dev/null +++ b/src/main/webapp/app/entities/activity/activity.tsx @@ -0,0 +1,228 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { byteSize, Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './activity.reducer'; + +export const Activity = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const activityList = useAppSelector(state => state.activity.entities); + const loading = useAppSelector(state => state.activity.loading); + const links = useAppSelector(state => state.activity.links); + const updateSuccess = useAppSelector(state => state.activity.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default Activity; diff --git a/src/main/webapp/app/entities/activity/index.tsx b/src/main/webapp/app/entities/activity/index.tsx new file mode 100644 index 0000000..a209451 --- /dev/null +++ b/src/main/webapp/app/entities/activity/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import Activity from './activity'; +import ActivityDetail from './activity-detail'; +import ActivityUpdate from './activity-update'; +import ActivityDeleteDialog from './activity-delete-dialog'; + +const ActivityRoutes = () => ( ++ Activities +
++ + +++ Create a new Activity + + +} + > + {activityList && activityList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {activityList.map((activity, i) => ( ++ ID ++ + Activity Time ++ + Duration ++ + Venue ++ + Details ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + Creator Profile ++ + Skill ++ + + + ))} + ++ + ++ {activity.activityTime ? +: null} + {activity.duration} +{activity.venue} +{activity.details} +{activity.createdBy} ++ {activity.createdDate ? +: null} + {activity.lastModifiedBy} ++ {activity.lastModifiedDate ? ( + ++ ) : null} + + {activity.creatorProfile ? ( + {activity.creatorProfile.id} + ) : ( + '' + )} + +{activity.skill ? {activity.skill.id} : ''} ++ ++ + + ++No Activities found+ )} + ++ +); + +export default ActivityRoutes; diff --git a/src/main/webapp/app/entities/code-tables/code-tables-delete-dialog.tsx b/src/main/webapp/app/entities/code-tables/code-tables-delete-dialog.tsx new file mode 100644 index 0000000..5650dec --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables-delete-dialog.tsx @@ -0,0 +1,62 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './code-tables.reducer'; + +export const CodeTablesDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const codeTablesEntity = useAppSelector(state => state.codeTables.entity); + const updateSuccess = useAppSelector(state => state.codeTables.updateSuccess); + + const handleClose = () => { + navigate('/code-tables'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(codeTablesEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default CodeTablesDeleteDialog; diff --git a/src/main/webapp/app/entities/code-tables/code-tables-detail.tsx b/src/main/webapp/app/entities/code-tables/code-tables-detail.tsx new file mode 100644 index 0000000..08e31aa --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables-detail.tsx @@ -0,0 +1,78 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './code-tables.reducer'; + +export const CodeTablesDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const codeTablesEntity = useAppSelector(state => state.codeTables.entity); + return ( ++ Confirm delete operation + +Are you sure you want to delete Code Tables {codeTablesEntity.id}? ++ + + ++
+ ); +}; + +export default CodeTablesDetail; diff --git a/src/main/webapp/app/entities/code-tables/code-tables-reducer.spec.ts b/src/main/webapp/app/entities/code-tables/code-tables-reducer.spec.ts new file mode 100644 index 0000000..ce9f135 --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables-reducer.spec.ts @@ -0,0 +1,265 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { ICodeTables, defaultValue } from 'app/shared/model/code-tables.model'; +import reducer, { + createEntity, + deleteEntity, + getEntities, + getEntity, + updateEntity, + partialUpdateEntity, + reset, +} from './code-tables.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Code Tables
++
+ + + + +- + ID +
+- {codeTablesEntity.id}
+- + Category +
+- {codeTablesEntity.category}
+- + Code Key +
+- {codeTablesEntity.codeKey}
+- + Code Value +
+- {codeTablesEntity.codeValue}
+- + Created By +
+- {codeTablesEntity.createdBy}
+- + Created Date +
+- + {codeTablesEntity.createdDate ?
+: null} + - + Last Modified By +
+- {codeTablesEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {codeTablesEntity.lastModifiedDate ? ( +
++ ) : null} + = { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_CODETABLES_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_CODETABLES actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_CODETABLES actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_CODETABLES actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_CODETABLES actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_CODETABLES actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/code-tables/code-tables-update.tsx b/src/main/webapp/app/entities/code-tables/code-tables-update.tsx new file mode 100644 index 0000000..343ed50 --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables-update.tsx @@ -0,0 +1,163 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { ICodeTables } from 'app/shared/model/code-tables.model'; +import { getEntity, updateEntity, createEntity, reset } from './code-tables.reducer'; + +export const CodeTablesUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const codeTablesEntity = useAppSelector(state => state.codeTables.entity); + const loading = useAppSelector(state => state.codeTables.loading); + const updating = useAppSelector(state => state.codeTables.updating); + const updateSuccess = useAppSelector(state => state.codeTables.updateSuccess); + + const handleClose = () => { + navigate('/code-tables'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...codeTablesEntity, + ...values, + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...codeTablesEntity, + createdDate: convertDateTimeFromServer(codeTablesEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(codeTablesEntity.lastModifiedDate), + }; + + return ( + ++ ); +}; + +export default CodeTablesUpdate; diff --git a/src/main/webapp/app/entities/code-tables/code-tables.reducer.ts b/src/main/webapp/app/entities/code-tables/code-tables.reducer.ts new file mode 100644 index 0000000..80c8dd2 --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { ICodeTables, defaultValue } from 'app/shared/model/code-tables.model'; + +const initialState: EntityState+
++ + Create or edit a Code Tables +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + + + + + + + + + = { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/code-tables'; + +// Actions + +export const getEntities = createAsyncThunk( + 'codeTables/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'codeTables/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'codeTables/create_entity', + async (entity: ICodeTables, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'codeTables/update_entity', + async (entity: ICodeTables, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'codeTables/partial_update_entity', + async (entity: ICodeTables, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'codeTables/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const CodeTablesSlice = createEntitySlice({ + name: 'codeTables', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = CodeTablesSlice.actions; + +// Reducer +export default CodeTablesSlice.reducer; diff --git a/src/main/webapp/app/entities/code-tables/code-tables.tsx b/src/main/webapp/app/entities/code-tables/code-tables.tsx new file mode 100644 index 0000000..54118a2 --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/code-tables.tsx @@ -0,0 +1,208 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './code-tables.reducer'; + +export const CodeTables = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const codeTablesList = useAppSelector(state => state.codeTables.entities); + const loading = useAppSelector(state => state.codeTables.loading); + const links = useAppSelector(state => state.codeTables.links); + const updateSuccess = useAppSelector(state => state.codeTables.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default CodeTables; diff --git a/src/main/webapp/app/entities/code-tables/index.tsx b/src/main/webapp/app/entities/code-tables/index.tsx new file mode 100644 index 0000000..c2eadc3 --- /dev/null +++ b/src/main/webapp/app/entities/code-tables/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import CodeTables from './code-tables'; +import CodeTablesDetail from './code-tables-detail'; +import CodeTablesUpdate from './code-tables-update'; +import CodeTablesDeleteDialog from './code-tables-delete-dialog'; + +const CodeTablesRoutes = () => ( ++ Code Tables +
++ + +++ Create a new Code Tables + + +} + > + {codeTablesList && codeTablesList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {codeTablesList.map((codeTables, i) => ( ++ ID ++ + Category ++ + Code Key ++ + Code Value ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + + + ))} + ++ + +{codeTables.category} +{codeTables.codeKey} +{codeTables.codeValue} +{codeTables.createdBy} ++ {codeTables.createdDate ? +: null} + {codeTables.lastModifiedBy} ++ {codeTables.lastModifiedDate ? ( + ++ ) : null} + + ++ + + ++No Code Tables found+ )} + ++ +); + +export default CodeTablesRoutes; diff --git a/src/main/webapp/app/entities/menu.tsx b/src/main/webapp/app/entities/menu.tsx index 56b6309..593c401 100644 --- a/src/main/webapp/app/entities/menu.tsx +++ b/src/main/webapp/app/entities/menu.tsx @@ -6,6 +6,27 @@ const EntitiesMenu = () => { return ( <> {/* prettier-ignore */} + + + + + + + {/* jhipster-needle-add-entity-to-menu - JHipster will add entities to the menu here */} > ); diff --git a/src/main/webapp/app/entities/message/index.tsx b/src/main/webapp/app/entities/message/index.tsx new file mode 100644 index 0000000..86eb258 --- /dev/null +++ b/src/main/webapp/app/entities/message/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import Message from './message'; +import MessageDetail from './message-detail'; +import MessageUpdate from './message-update'; +import MessageDeleteDialog from './message-delete-dialog'; + +const MessageRoutes = () => ( +} /> + } /> + + +} /> + } /> + } /> + + +); + +export default MessageRoutes; diff --git a/src/main/webapp/app/entities/message/message-delete-dialog.tsx b/src/main/webapp/app/entities/message/message-delete-dialog.tsx new file mode 100644 index 0000000..25dede1 --- /dev/null +++ b/src/main/webapp/app/entities/message/message-delete-dialog.tsx @@ -0,0 +1,62 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './message.reducer'; + +export const MessageDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const messageEntity = useAppSelector(state => state.message.entity); + const updateSuccess = useAppSelector(state => state.message.updateSuccess); + + const handleClose = () => { + navigate('/message'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(messageEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default MessageDeleteDialog; diff --git a/src/main/webapp/app/entities/message/message-detail.tsx b/src/main/webapp/app/entities/message/message-detail.tsx new file mode 100644 index 0000000..0a57f62 --- /dev/null +++ b/src/main/webapp/app/entities/message/message-detail.tsx @@ -0,0 +1,82 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { byteSize, TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './message.reducer'; + +export const MessageDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const messageEntity = useAppSelector(state => state.message.entity); + return ( ++ Confirm delete operation + +Are you sure you want to delete Message {messageEntity.id}? ++ + + ++
+ ); +}; + +export default MessageDetail; diff --git a/src/main/webapp/app/entities/message/message-reducer.spec.ts b/src/main/webapp/app/entities/message/message-reducer.spec.ts new file mode 100644 index 0000000..883bbf2 --- /dev/null +++ b/src/main/webapp/app/entities/message/message-reducer.spec.ts @@ -0,0 +1,257 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { IMessage, defaultValue } from 'app/shared/model/message.model'; +import reducer, { createEntity, deleteEntity, getEntities, getEntity, updateEntity, partialUpdateEntity, reset } from './message.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Message
++
+ + + + +- + ID +
+- {messageEntity.id}
+- + Content +
+- {messageEntity.content}
+- + Sent At +
+- {messageEntity.sentAt ?
+: null} - + Is Deleted +
+- {messageEntity.isDeleted ? 'true' : 'false'}
+- + Created By +
+- {messageEntity.createdBy}
+- + Created Date +
+- + {messageEntity.createdDate ?
+: null} + - + Last Modified By +
+- {messageEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {messageEntity.lastModifiedDate ? ( +
++ ) : null} + - Sender Profile
+- {messageEntity.senderProfile ? messageEntity.senderProfile.id : ''}
+- Receiver Profile
+- {messageEntity.receiverProfile ? messageEntity.receiverProfile.id : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_MESSAGE_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_MESSAGE actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_MESSAGE actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_MESSAGE actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_MESSAGE actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_MESSAGE actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/message/message-update.tsx b/src/main/webapp/app/entities/message/message-update.tsx new file mode 100644 index 0000000..5f64260 --- /dev/null +++ b/src/main/webapp/app/entities/message/message-update.tsx @@ -0,0 +1,193 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntities as getUserProfiles } from 'app/entities/user-profile/user-profile.reducer'; +import { IMessage } from 'app/shared/model/message.model'; +import { getEntity, updateEntity, createEntity, reset } from './message.reducer'; + +export const MessageUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const userProfiles = useAppSelector(state => state.userProfile.entities); + const messageEntity = useAppSelector(state => state.message.entity); + const loading = useAppSelector(state => state.message.loading); + const updating = useAppSelector(state => state.message.updating); + const updateSuccess = useAppSelector(state => state.message.updateSuccess); + + const handleClose = () => { + navigate('/message'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getUserProfiles({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.sentAt = convertDateTimeToServer(values.sentAt); + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...messageEntity, + ...values, + senderProfile: userProfiles.find(it => it.id.toString() === values.senderProfile?.toString()), + receiverProfile: userProfiles.find(it => it.id.toString() === values.receiverProfile?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + sentAt: displayDefaultDateTime(), + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...messageEntity, + sentAt: convertDateTimeFromServer(messageEntity.sentAt), + createdDate: convertDateTimeFromServer(messageEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(messageEntity.lastModifiedDate), + senderProfile: messageEntity?.senderProfile?.id, + receiverProfile: messageEntity?.receiverProfile?.id, + }; + + return ( + ++ ); +}; + +export default MessageUpdate; diff --git a/src/main/webapp/app/entities/message/message.reducer.ts b/src/main/webapp/app/entities/message/message.reducer.ts new file mode 100644 index 0000000..32f01cf --- /dev/null +++ b/src/main/webapp/app/entities/message/message.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { IMessage, defaultValue } from 'app/shared/model/message.model'; + +const initialState: EntityState+
++ + Create or edit a Message +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + + + + + + + + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + ++ + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/messages'; + +// Actions + +export const getEntities = createAsyncThunk( + 'message/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'message/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'message/create_entity', + async (entity: IMessage, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'message/update_entity', + async (entity: IMessage, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'message/partial_update_entity', + async (entity: IMessage, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'message/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const MessageSlice = createEntitySlice({ + name: 'message', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = MessageSlice.actions; + +// Reducer +export default MessageSlice.reducer; diff --git a/src/main/webapp/app/entities/message/message.tsx b/src/main/webapp/app/entities/message/message.tsx new file mode 100644 index 0000000..f054645 --- /dev/null +++ b/src/main/webapp/app/entities/message/message.tsx @@ -0,0 +1,226 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { byteSize, Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './message.reducer'; + +export const Message = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const messageList = useAppSelector(state => state.message.entities); + const loading = useAppSelector(state => state.message.loading); + const links = useAppSelector(state => state.message.links); + const updateSuccess = useAppSelector(state => state.message.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default Message; diff --git a/src/main/webapp/app/entities/notification/index.tsx b/src/main/webapp/app/entities/notification/index.tsx new file mode 100644 index 0000000..b498f63 --- /dev/null +++ b/src/main/webapp/app/entities/notification/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import Notification from './notification'; +import NotificationDetail from './notification-detail'; +import NotificationUpdate from './notification-update'; +import NotificationDeleteDialog from './notification-delete-dialog'; + +const NotificationRoutes = () => ( ++ Messages +
++ + +++ Create a new Message + + +} + > + {messageList && messageList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {messageList.map((message, i) => ( ++ ID ++ + Content ++ + Sent At ++ + Is Deleted ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + Sender Profile ++ + Receiver Profile ++ + + + ))} + ++ + +{message.content} +{message.sentAt ? +: null} {message.isDeleted ? 'true' : 'false'} +{message.createdBy} +{message.createdDate ? +: null} {message.lastModifiedBy} ++ {message.lastModifiedDate ? ( + ++ ) : null} + + {message.senderProfile ? ( + {message.senderProfile.id} + ) : ( + '' + )} + ++ {message.receiverProfile ? ( + {message.receiverProfile.id} + ) : ( + '' + )} + ++ ++ + + ++No Messages found+ )} + ++ +); + +export default NotificationRoutes; diff --git a/src/main/webapp/app/entities/notification/notification-delete-dialog.tsx b/src/main/webapp/app/entities/notification/notification-delete-dialog.tsx new file mode 100644 index 0000000..e5507a0 --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification-delete-dialog.tsx @@ -0,0 +1,64 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './notification.reducer'; + +export const NotificationDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const notificationEntity = useAppSelector(state => state.notification.entity); + const updateSuccess = useAppSelector(state => state.notification.updateSuccess); + + const handleClose = () => { + navigate('/notification'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(notificationEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default NotificationDeleteDialog; diff --git a/src/main/webapp/app/entities/notification/notification-detail.tsx b/src/main/webapp/app/entities/notification/notification-detail.tsx new file mode 100644 index 0000000..cb82657 --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification-detail.tsx @@ -0,0 +1,84 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { byteSize, TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './notification.reducer'; + +export const NotificationDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const notificationEntity = useAppSelector(state => state.notification.entity); + return ( ++ Confirm delete operation + ++ Are you sure you want to delete Notification {notificationEntity.id}? + ++ + + ++
+ ); +}; + +export default NotificationDetail; diff --git a/src/main/webapp/app/entities/notification/notification-reducer.spec.ts b/src/main/webapp/app/entities/notification/notification-reducer.spec.ts new file mode 100644 index 0000000..4ccb7cb --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification-reducer.spec.ts @@ -0,0 +1,265 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { INotification, defaultValue } from 'app/shared/model/notification.model'; +import reducer, { + createEntity, + deleteEntity, + getEntities, + getEntity, + updateEntity, + partialUpdateEntity, + reset, +} from './notification.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Notification
++
+ + + + +- + ID +
+- {notificationEntity.id}
+- + Notification Ref Id +
+- {notificationEntity.notificationRefId}
+- + Content +
+- {notificationEntity.content}
+- + Is Read +
+- {notificationEntity.isRead ? 'true' : 'false'}
+- + Created By +
+- {notificationEntity.createdBy}
+- + Created Date +
+- + {notificationEntity.createdDate ? ( +
++ ) : null} + - + Last Modified By +
+- {notificationEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {notificationEntity.lastModifiedDate ? ( +
++ ) : null} + - User Profile
+- {notificationEntity.userProfile ? notificationEntity.userProfile.id : ''}
+- Type
+- {notificationEntity.type ? notificationEntity.type.id : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_NOTIFICATION_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_NOTIFICATION actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_NOTIFICATION actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_NOTIFICATION actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_NOTIFICATION actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_NOTIFICATION actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/notification/notification-update.tsx b/src/main/webapp/app/entities/notification/notification-update.tsx new file mode 100644 index 0000000..7914c92 --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification-update.tsx @@ -0,0 +1,175 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntities as getUserProfiles } from 'app/entities/user-profile/user-profile.reducer'; +import { ICodeTables } from 'app/shared/model/code-tables.model'; +import { getEntities as getCodeTables } from 'app/entities/code-tables/code-tables.reducer'; +import { INotification } from 'app/shared/model/notification.model'; +import { getEntity, updateEntity, createEntity, reset } from './notification.reducer'; + +export const NotificationUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const userProfiles = useAppSelector(state => state.userProfile.entities); + const codeTables = useAppSelector(state => state.codeTables.entities); + const notificationEntity = useAppSelector(state => state.notification.entity); + const loading = useAppSelector(state => state.notification.loading); + const updating = useAppSelector(state => state.notification.updating); + const updateSuccess = useAppSelector(state => state.notification.updateSuccess); + + const handleClose = () => { + navigate('/notification'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getUserProfiles({})); + dispatch(getCodeTables({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...notificationEntity, + ...values, + userProfile: userProfiles.find(it => it.id.toString() === values.userProfile?.toString()), + type: codeTables.find(it => it.id.toString() === values.type?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...notificationEntity, + createdDate: convertDateTimeFromServer(notificationEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(notificationEntity.lastModifiedDate), + userProfile: notificationEntity?.userProfile?.id, + type: notificationEntity?.type?.id, + }; + + return ( + ++ ); +}; + +export default NotificationUpdate; diff --git a/src/main/webapp/app/entities/notification/notification.reducer.ts b/src/main/webapp/app/entities/notification/notification.reducer.ts new file mode 100644 index 0000000..d1d3e9c --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { INotification, defaultValue } from 'app/shared/model/notification.model'; + +const initialState: EntityState+
++ + Create or edit a Notification +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + + + + + + + + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + ++ + {codeTables + ? codeTables.map(otherEntity => ( + + )) + : null} + + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/notifications'; + +// Actions + +export const getEntities = createAsyncThunk( + 'notification/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'notification/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'notification/create_entity', + async (entity: INotification, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'notification/update_entity', + async (entity: INotification, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'notification/partial_update_entity', + async (entity: INotification, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'notification/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const NotificationSlice = createEntitySlice({ + name: 'notification', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = NotificationSlice.actions; + +// Reducer +export default NotificationSlice.reducer; diff --git a/src/main/webapp/app/entities/notification/notification.tsx b/src/main/webapp/app/entities/notification/notification.tsx new file mode 100644 index 0000000..d5bf614 --- /dev/null +++ b/src/main/webapp/app/entities/notification/notification.tsx @@ -0,0 +1,230 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { byteSize, Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './notification.reducer'; + +export const Notification = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const notificationList = useAppSelector(state => state.notification.entities); + const loading = useAppSelector(state => state.notification.loading); + const links = useAppSelector(state => state.notification.links); + const updateSuccess = useAppSelector(state => state.notification.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default Notification; diff --git a/src/main/webapp/app/entities/reducers.ts b/src/main/webapp/app/entities/reducers.ts index efad4f9..b9aa7ca 100644 --- a/src/main/webapp/app/entities/reducers.ts +++ b/src/main/webapp/app/entities/reducers.ts @@ -1,6 +1,20 @@ +import codeTables from 'app/entities/code-tables/code-tables.reducer'; +import userProfile from 'app/entities/user-profile/user-profile.reducer'; +import skill from 'app/entities/skill/skill.reducer'; +import message from 'app/entities/message/message.reducer'; +import activity from 'app/entities/activity/activity.reducer'; +import activityInvite from 'app/entities/activity-invite/activity-invite.reducer'; +import notification from 'app/entities/notification/notification.reducer'; /* jhipster-needle-add-reducer-import - JHipster will add reducer here */ const entitiesReducers = { + codeTables, + userProfile, + skill, + message, + activity, + activityInvite, + notification, /* jhipster-needle-add-reducer-combine - JHipster will add reducer here */ }; diff --git a/src/main/webapp/app/entities/routes.tsx b/src/main/webapp/app/entities/routes.tsx index 84e142c..d72837b 100644 --- a/src/main/webapp/app/entities/routes.tsx +++ b/src/main/webapp/app/entities/routes.tsx @@ -3,6 +3,13 @@ import { Route } from 'react-router-dom'; import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; +import CodeTables from './code-tables'; +import UserProfile from './user-profile'; +import Skill from './skill'; +import Message from './message'; +import Activity from './activity'; +import ActivityInvite from './activity-invite'; +import Notification from './notification'; /* jhipster-needle-add-route-import - JHipster will add routes here */ export default () => { @@ -10,6 +17,13 @@ export default () => {+ Notifications +
++ + +++ Create a new Notification + + +} + > + {notificationList && notificationList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {notificationList.map((notification, i) => ( ++ ID ++ + Notification Ref Id ++ + Content ++ + Is Read ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + User Profile ++ + Type ++ + + + ))} + ++ + +{notification.notificationRefId} +{notification.content} +{notification.isRead ? 'true' : 'false'} +{notification.createdBy} ++ {notification.createdDate ? ( + ++ ) : null} + {notification.lastModifiedBy} ++ {notification.lastModifiedDate ? ( + ++ ) : null} + + {notification.userProfile ? ( + {notification.userProfile.id} + ) : ( + '' + )} + +{notification.type ? {notification.type.id} : ''} ++ ++ + + ++No Notifications found+ )} + +diff --git a/src/main/webapp/app/entities/skill/index.tsx b/src/main/webapp/app/entities/skill/index.tsx new file mode 100644 index 0000000..6d9603b --- /dev/null +++ b/src/main/webapp/app/entities/skill/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import Skill from './skill'; +import SkillDetail from './skill-detail'; +import SkillUpdate from './skill-update'; +import SkillDeleteDialog from './skill-delete-dialog'; + +const SkillRoutes = () => ( +{/* prettier-ignore */} + } /> + } /> + } /> + } /> + } /> + } /> + } /> {/* jhipster-needle-add-route-path - JHipster will add routes here */} + +); + +export default SkillRoutes; diff --git a/src/main/webapp/app/entities/skill/skill-delete-dialog.tsx b/src/main/webapp/app/entities/skill/skill-delete-dialog.tsx new file mode 100644 index 0000000..da7fb1a --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill-delete-dialog.tsx @@ -0,0 +1,62 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './skill.reducer'; + +export const SkillDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const skillEntity = useAppSelector(state => state.skill.entity); + const updateSuccess = useAppSelector(state => state.skill.updateSuccess); + + const handleClose = () => { + navigate('/skill'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(skillEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default SkillDeleteDialog; diff --git a/src/main/webapp/app/entities/skill/skill-detail.tsx b/src/main/webapp/app/entities/skill/skill-detail.tsx new file mode 100644 index 0000000..15b7fdf --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill-detail.tsx @@ -0,0 +1,76 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './skill.reducer'; + +export const SkillDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const skillEntity = useAppSelector(state => state.skill.entity); + return ( ++ Confirm delete operation + +Are you sure you want to delete Skill {skillEntity.id}? ++ + + ++
+ ); +}; + +export default SkillDetail; diff --git a/src/main/webapp/app/entities/skill/skill-reducer.spec.ts b/src/main/webapp/app/entities/skill/skill-reducer.spec.ts new file mode 100644 index 0000000..a47b11e --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill-reducer.spec.ts @@ -0,0 +1,257 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { ISkill, defaultValue } from 'app/shared/model/skill.model'; +import reducer, { createEntity, deleteEntity, getEntities, getEntity, updateEntity, partialUpdateEntity, reset } from './skill.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ Skill
++
+ + + + +- + ID +
+- {skillEntity.id}
+- + Skill Name +
+- {skillEntity.skillName}
+- + Individual Skill Desc +
+- {skillEntity.individualSkillDesc}
+- + Years Of Exp +
+- {skillEntity.yearsOfExp}
+- + Created By +
+- {skillEntity.createdBy}
+- + Created Date +
+- {skillEntity.createdDate ?
+: null} - + Last Modified By +
+- {skillEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {skillEntity.lastModifiedDate ?
+: null} + - User Profile
+- {skillEntity.userProfile ? skillEntity.userProfile.id : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_SKILL_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_SKILL actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_SKILL actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_SKILL actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_SKILL actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_SKILL actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/skill/skill-update.tsx b/src/main/webapp/app/entities/skill/skill-update.tsx new file mode 100644 index 0000000..9045b50 --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill-update.tsx @@ -0,0 +1,185 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntities as getUserProfiles } from 'app/entities/user-profile/user-profile.reducer'; +import { ISkill } from 'app/shared/model/skill.model'; +import { getEntity, updateEntity, createEntity, reset } from './skill.reducer'; + +export const SkillUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const userProfiles = useAppSelector(state => state.userProfile.entities); + const skillEntity = useAppSelector(state => state.skill.entity); + const loading = useAppSelector(state => state.skill.loading); + const updating = useAppSelector(state => state.skill.updating); + const updateSuccess = useAppSelector(state => state.skill.updateSuccess); + + const handleClose = () => { + navigate('/skill'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getUserProfiles({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + if (values.yearsOfExp !== undefined && typeof values.yearsOfExp !== 'number') { + values.yearsOfExp = Number(values.yearsOfExp); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...skillEntity, + ...values, + userProfile: userProfiles.find(it => it.id.toString() === values.userProfile?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...skillEntity, + createdDate: convertDateTimeFromServer(skillEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(skillEntity.lastModifiedDate), + userProfile: skillEntity?.userProfile?.id, + }; + + return ( + ++ ); +}; + +export default SkillUpdate; diff --git a/src/main/webapp/app/entities/skill/skill.reducer.ts b/src/main/webapp/app/entities/skill/skill.reducer.ts new file mode 100644 index 0000000..7457080 --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { ISkill, defaultValue } from 'app/shared/model/skill.model'; + +const initialState: EntityState+
++ + Create or edit a Skill +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + isNumber(v) || 'This field should be a number.', + }} + /> + + + + + + + {userProfiles + ? userProfiles.map(otherEntity => ( + + )) + : null} + + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/skills'; + +// Actions + +export const getEntities = createAsyncThunk( + 'skill/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'skill/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'skill/create_entity', + async (entity: ISkill, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'skill/update_entity', + async (entity: ISkill, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'skill/partial_update_entity', + async (entity: ISkill, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'skill/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const SkillSlice = createEntitySlice({ + name: 'skill', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = SkillSlice.actions; + +// Reducer +export default SkillSlice.reducer; diff --git a/src/main/webapp/app/entities/skill/skill.tsx b/src/main/webapp/app/entities/skill/skill.tsx new file mode 100644 index 0000000..1ab2986 --- /dev/null +++ b/src/main/webapp/app/entities/skill/skill.tsx @@ -0,0 +1,208 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './skill.reducer'; + +export const Skill = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const skillList = useAppSelector(state => state.skill.entities); + const loading = useAppSelector(state => state.skill.loading); + const links = useAppSelector(state => state.skill.links); + const updateSuccess = useAppSelector(state => state.skill.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default Skill; diff --git a/src/main/webapp/app/entities/user-profile/index.tsx b/src/main/webapp/app/entities/user-profile/index.tsx new file mode 100644 index 0000000..ad35cc9 --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { Route } from 'react-router-dom'; + +import ErrorBoundaryRoutes from 'app/shared/error/error-boundary-routes'; + +import UserProfile from './user-profile'; +import UserProfileDetail from './user-profile-detail'; +import UserProfileUpdate from './user-profile-update'; +import UserProfileDeleteDialog from './user-profile-delete-dialog'; + +const UserProfileRoutes = () => ( ++ Skills +
++ + +++ Create a new Skill + + +} + > + {skillList && skillList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {skillList.map((skill, i) => ( ++ ID ++ + Skill Name ++ + Individual Skill Desc ++ + Years Of Exp ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + User Profile ++ + + + ))} + ++ + +{skill.skillName} +{skill.individualSkillDesc} +{skill.yearsOfExp} +{skill.createdBy} +{skill.createdDate ? +: null} {skill.lastModifiedBy} ++ {skill.lastModifiedDate ? +: null} + {skill.userProfile ? {skill.userProfile.id} : ''} ++ ++ + + ++No Skills found+ )} + ++ +); + +export default UserProfileRoutes; diff --git a/src/main/webapp/app/entities/user-profile/user-profile-delete-dialog.tsx b/src/main/webapp/app/entities/user-profile/user-profile-delete-dialog.tsx new file mode 100644 index 0000000..306508e --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile-delete-dialog.tsx @@ -0,0 +1,64 @@ +import React, { useEffect, useState } from 'react'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; +import { Modal, ModalHeader, ModalBody, ModalFooter, Button } from 'reactstrap'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { useAppDispatch, useAppSelector } from 'app/config/store'; +import { getEntity, deleteEntity } from './user-profile.reducer'; + +export const UserProfileDeleteDialog = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + const navigate = useNavigate(); + const { id } = useParams<'id'>(); + + const [loadModal, setLoadModal] = useState(false); + + useEffect(() => { + dispatch(getEntity(id)); + setLoadModal(true); + }, []); + + const userProfileEntity = useAppSelector(state => state.userProfile.entity); + const updateSuccess = useAppSelector(state => state.userProfile.updateSuccess); + + const handleClose = () => { + navigate('/user-profile'); + }; + + useEffect(() => { + if (updateSuccess && loadModal) { + handleClose(); + setLoadModal(false); + } + }, [updateSuccess]); + + const confirmDelete = () => { + dispatch(deleteEntity(userProfileEntity.id)); + }; + + return ( +} /> + } /> + + +} /> + } /> + } /> + + + ); +}; + +export default UserProfileDeleteDialog; diff --git a/src/main/webapp/app/entities/user-profile/user-profile-detail.tsx b/src/main/webapp/app/entities/user-profile/user-profile-detail.tsx new file mode 100644 index 0000000..7065468 --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile-detail.tsx @@ -0,0 +1,86 @@ +import React, { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { Button, Row, Col } from 'reactstrap'; +import { TextFormat } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntity } from './user-profile.reducer'; + +export const UserProfileDetail = () => { + const dispatch = useAppDispatch(); + + const { id } = useParams<'id'>(); + + useEffect(() => { + dispatch(getEntity(id)); + }, []); + + const userProfileEntity = useAppSelector(state => state.userProfile.entity); + return ( ++ Confirm delete operation + ++ Are you sure you want to delete User Profile {userProfileEntity.id}? + ++ + + ++
+ ); +}; + +export default UserProfileDetail; diff --git a/src/main/webapp/app/entities/user-profile/user-profile-reducer.spec.ts b/src/main/webapp/app/entities/user-profile/user-profile-reducer.spec.ts new file mode 100644 index 0000000..852169d --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile-reducer.spec.ts @@ -0,0 +1,265 @@ +import axios from 'axios'; + +import { configureStore } from '@reduxjs/toolkit'; +import sinon from 'sinon'; +import { parseHeaderForLinks } from 'react-jhipster'; + +import { EntityState } from 'app/shared/reducers/reducer.utils'; +import { IUserProfile, defaultValue } from 'app/shared/model/user-profile.model'; +import reducer, { + createEntity, + deleteEntity, + getEntities, + getEntity, + updateEntity, + partialUpdateEntity, + reset, +} from './user-profile.reducer'; + +describe('Entities reducer tests', () => { + function isEmpty(element): boolean { + if (element instanceof Array) { + return element.length === 0; + } else { + return Object.keys(element).length === 0; + } + } + + const initialState: EntityState+ User Profile
++
+ + + + +- + ID +
+- {userProfileEntity.id}
+- + Nickname +
+- {userProfileEntity.nickname}
+- + Job Role +
+- {userProfileEntity.jobRole}
+- + About Me +
+- {userProfileEntity.aboutMe}
+- + Profile Picture +
+- {userProfileEntity.profilePicture}
+- + Created By +
+- {userProfileEntity.createdBy}
+- + Created Date +
+- + {userProfileEntity.createdDate ? ( +
++ ) : null} + - + Last Modified By +
+- {userProfileEntity.lastModifiedBy}
+- + Last Modified Date +
+- + {userProfileEntity.lastModifiedDate ? ( +
++ ) : null} + - User
+- {userProfileEntity.user ? userProfileEntity.user.login : ''}
+= { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { + next: 0, + }, + totalItems: 0, + updating: false, + updateSuccess: false, + }; + + function testInitialState(state) { + expect(state).toMatchObject({ + loading: false, + errorMessage: null, + updating: false, + updateSuccess: false, + }); + expect(isEmpty(state.entities)); + expect(isEmpty(state.entity)); + } + + function testMultipleTypes(types, payload, testFunction, error?) { + types.forEach(e => { + testFunction(reducer(undefined, { type: e, payload, error })); + }); + } + + describe('Common', () => { + it('should return the initial state', () => { + testInitialState(reducer(undefined, { type: '' })); + }); + }); + + describe('Requests', () => { + it('should set state to loading', () => { + testMultipleTypes([getEntities.pending.type, getEntity.pending.type], {}, state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + loading: true, + }); + }); + }); + + it('should set state to updating', () => { + testMultipleTypes( + [createEntity.pending.type, updateEntity.pending.type, partialUpdateEntity.pending.type, deleteEntity.pending.type], + {}, + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: true, + }); + }, + ); + }); + + it('should reset the state', () => { + expect(reducer({ ...initialState, loading: true }, reset())).toEqual({ + ...initialState, + }); + }); + }); + + describe('Failures', () => { + it('should set a message in errorMessage', () => { + testMultipleTypes( + [ + getEntities.rejected.type, + getEntity.rejected.type, + createEntity.rejected.type, + updateEntity.rejected.type, + partialUpdateEntity.rejected.type, + deleteEntity.rejected.type, + ], + 'some message', + state => { + expect(state).toMatchObject({ + errorMessage: null, + updateSuccess: false, + updating: false, + }); + }, + { + message: 'error message', + }, + ); + }); + }); + + describe('Successes', () => { + it('should fetch all entities', () => { + const payload = { data: [{ 1: 'fake1' }, { 2: 'fake2' }], headers: { 'x-total-count': 123, link: ';' } }; + const links = parseHeaderForLinks(payload.headers.link); + expect( + reducer(undefined, { + type: getEntities.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + links, + loading: false, + totalItems: payload.headers['x-total-count'], + entities: payload.data, + }); + }); + + it('should fetch a single entity', () => { + const payload = { data: { 1: 'fake1' } }; + expect( + reducer(undefined, { + type: getEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + loading: false, + entity: payload.data, + }); + }); + + it('should create/update entity', () => { + const payload = { data: 'fake payload' }; + expect( + reducer(undefined, { + type: createEntity.fulfilled.type, + payload, + }), + ).toEqual({ + ...initialState, + updating: false, + updateSuccess: true, + entity: payload.data, + }); + }); + + it('should delete entity', () => { + const payload = 'fake payload'; + const toTest = reducer(undefined, { + type: deleteEntity.fulfilled.type, + payload, + }); + expect(toTest).toMatchObject({ + updating: false, + updateSuccess: true, + }); + }); + }); + + describe('Actions', () => { + let store; + + const resolvedObject = { value: 'whatever' }; + const getState = jest.fn(); + const dispatch = jest.fn(); + const extra = {}; + beforeEach(() => { + store = configureStore({ + reducer: (state = [], action) => [...state, action], + }); + axios.get = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.post = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.put = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.patch = sinon.stub().returns(Promise.resolve(resolvedObject)); + axios.delete = sinon.stub().returns(Promise.resolve(resolvedObject)); + }); + + it('dispatches FETCH_USERPROFILE_LIST actions', async () => { + const arg = {}; + + const result = await getEntities(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntities.fulfilled.match(result)).toBe(true); + }); + + it('dispatches FETCH_USERPROFILE actions', async () => { + const arg = 42666; + + const result = await getEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(getEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches CREATE_USERPROFILE actions', async () => { + const arg = { id: 456 }; + + const result = await createEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(createEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches UPDATE_USERPROFILE actions', async () => { + const arg = { id: 456 }; + + const result = await updateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(updateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches PARTIAL_UPDATE_USERPROFILE actions', async () => { + const arg = { id: 123 }; + + const result = await partialUpdateEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(partialUpdateEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches DELETE_USERPROFILE actions', async () => { + const arg = 42666; + + const result = await deleteEntity(arg)(dispatch, getState, extra); + + const pendingAction = dispatch.mock.calls[0][0]; + expect(pendingAction.meta.requestStatus).toBe('pending'); + expect(deleteEntity.fulfilled.match(result)).toBe(true); + }); + + it('dispatches RESET actions', async () => { + await store.dispatch(reset()); + expect(store.getState()).toEqual([expect.any(Object), expect.objectContaining(reset())]); + }); + }); +}); diff --git a/src/main/webapp/app/entities/user-profile/user-profile-update.tsx b/src/main/webapp/app/entities/user-profile/user-profile-update.tsx new file mode 100644 index 0000000..737d7e0 --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile-update.tsx @@ -0,0 +1,191 @@ +import React, { useState, useEffect } from 'react'; +import { Link, useNavigate, useParams } from 'react-router-dom'; +import { Button, Row, Col, FormText } from 'reactstrap'; +import { isNumber, ValidatedField, ValidatedForm } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +import { convertDateTimeFromServer, convertDateTimeToServer, displayDefaultDateTime } from 'app/shared/util/date-utils'; +import { mapIdList } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { IUser } from 'app/shared/model/user.model'; +import { getUsers } from 'app/modules/administration/user-management/user-management.reducer'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { getEntity, updateEntity, createEntity, reset } from './user-profile.reducer'; + +export const UserProfileUpdate = () => { + const dispatch = useAppDispatch(); + + const navigate = useNavigate(); + + const { id } = useParams<'id'>(); + const isNew = id === undefined; + + const users = useAppSelector(state => state.userManagement.users); + const userProfileEntity = useAppSelector(state => state.userProfile.entity); + const loading = useAppSelector(state => state.userProfile.loading); + const updating = useAppSelector(state => state.userProfile.updating); + const updateSuccess = useAppSelector(state => state.userProfile.updateSuccess); + + const handleClose = () => { + navigate('/user-profile'); + }; + + useEffect(() => { + if (!isNew) { + dispatch(getEntity(id)); + } + + dispatch(getUsers({})); + }, []); + + useEffect(() => { + if (updateSuccess) { + handleClose(); + } + }, [updateSuccess]); + + // eslint-disable-next-line complexity + const saveEntity = values => { + if (values.id !== undefined && typeof values.id !== 'number') { + values.id = Number(values.id); + } + values.createdDate = convertDateTimeToServer(values.createdDate); + values.lastModifiedDate = convertDateTimeToServer(values.lastModifiedDate); + + const entity = { + ...userProfileEntity, + ...values, + user: users.find(it => it.id.toString() === values.user?.toString()), + }; + + if (isNew) { + dispatch(createEntity(entity)); + } else { + dispatch(updateEntity(entity)); + } + }; + + const defaultValues = () => + isNew + ? { + createdDate: displayDefaultDateTime(), + lastModifiedDate: displayDefaultDateTime(), + } + : { + ...userProfileEntity, + createdDate: convertDateTimeFromServer(userProfileEntity.createdDate), + lastModifiedDate: convertDateTimeFromServer(userProfileEntity.lastModifiedDate), + user: userProfileEntity?.user?.id, + }; + + return ( + ++ ); +}; + +export default UserProfileUpdate; diff --git a/src/main/webapp/app/entities/user-profile/user-profile.reducer.ts b/src/main/webapp/app/entities/user-profile/user-profile.reducer.ts new file mode 100644 index 0000000..3eae414 --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile.reducer.ts @@ -0,0 +1,124 @@ +import axios from 'axios'; +import { createAsyncThunk, isFulfilled, isPending } from '@reduxjs/toolkit'; +import { loadMoreDataWhenScrolled, parseHeaderForLinks } from 'react-jhipster'; +import { cleanEntity } from 'app/shared/util/entity-utils'; +import { IQueryParams, createEntitySlice, EntityState, serializeAxiosError } from 'app/shared/reducers/reducer.utils'; +import { IUserProfile, defaultValue } from 'app/shared/model/user-profile.model'; + +const initialState: EntityState+
++ + Create or edit a User Profile +
+ ++
++ {loading ? ( + Loading...
+ ) : ( ++ {!isNew ? + )} + +: null} + + + + + + + + + + + {users + ? users.map(otherEntity => ( + + )) + : null} + +This field is required. + + + += { + loading: false, + errorMessage: null, + entities: [], + entity: defaultValue, + links: { next: 0 }, + updating: false, + totalItems: 0, + updateSuccess: false, +}; + +const apiUrl = 'api/user-profiles'; + +// Actions + +export const getEntities = createAsyncThunk( + 'userProfile/fetch_entity_list', + async ({ page, size, sort }: IQueryParams) => { + const requestUrl = `${apiUrl}?${sort ? `page=${page}&size=${size}&sort=${sort}&` : ''}cacheBuster=${new Date().getTime()}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const getEntity = createAsyncThunk( + 'userProfile/fetch_entity', + async (id: string | number) => { + const requestUrl = `${apiUrl}/${id}`; + return axios.get (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +export const createEntity = createAsyncThunk( + 'userProfile/create_entity', + async (entity: IUserProfile, thunkAPI) => { + return axios.post (apiUrl, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const updateEntity = createAsyncThunk( + 'userProfile/update_entity', + async (entity: IUserProfile, thunkAPI) => { + return axios.put (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const partialUpdateEntity = createAsyncThunk( + 'userProfile/partial_update_entity', + async (entity: IUserProfile, thunkAPI) => { + return axios.patch (`${apiUrl}/${entity.id}`, cleanEntity(entity)); + }, + { serializeError: serializeAxiosError }, +); + +export const deleteEntity = createAsyncThunk( + 'userProfile/delete_entity', + async (id: string | number, thunkAPI) => { + const requestUrl = `${apiUrl}/${id}`; + return await axios.delete (requestUrl); + }, + { serializeError: serializeAxiosError }, +); + +// slice + +export const UserProfileSlice = createEntitySlice({ + name: 'userProfile', + initialState, + extraReducers(builder) { + builder + .addCase(getEntity.fulfilled, (state, action) => { + state.loading = false; + state.entity = action.payload.data; + }) + .addCase(deleteEntity.fulfilled, state => { + state.updating = false; + state.updateSuccess = true; + state.entity = {}; + }) + .addMatcher(isFulfilled(getEntities), (state, action) => { + const { data, headers } = action.payload; + const links = parseHeaderForLinks(headers.link); + + return { + ...state, + loading: false, + links, + entities: loadMoreDataWhenScrolled(state.entities, data, links), + totalItems: parseInt(headers['x-total-count'], 10), + }; + }) + .addMatcher(isFulfilled(createEntity, updateEntity, partialUpdateEntity), (state, action) => { + state.updating = false; + state.loading = false; + state.updateSuccess = true; + state.entity = action.payload.data; + }) + .addMatcher(isPending(getEntities, getEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.loading = true; + }) + .addMatcher(isPending(createEntity, updateEntity, partialUpdateEntity, deleteEntity), state => { + state.errorMessage = null; + state.updateSuccess = false; + state.updating = true; + }); + }, +}); + +export const { reset } = UserProfileSlice.actions; + +// Reducer +export default UserProfileSlice.reducer; diff --git a/src/main/webapp/app/entities/user-profile/user-profile.tsx b/src/main/webapp/app/entities/user-profile/user-profile.tsx new file mode 100644 index 0000000..07d970f --- /dev/null +++ b/src/main/webapp/app/entities/user-profile/user-profile.tsx @@ -0,0 +1,216 @@ +import React, { useState, useEffect } from 'react'; +import InfiniteScroll from 'react-infinite-scroll-component'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { Button, Table } from 'reactstrap'; +import { Translate, TextFormat, getPaginationState } from 'react-jhipster'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'; +import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants'; +import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/util/pagination.constants'; +import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils'; +import { useAppDispatch, useAppSelector } from 'app/config/store'; + +import { getEntities, reset } from './user-profile.reducer'; + +export const UserProfile = () => { + const dispatch = useAppDispatch(); + + const pageLocation = useLocation(); + + const [paginationState, setPaginationState] = useState( + overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, 'id'), pageLocation.search), + ); + const [sorting, setSorting] = useState(false); + + const userProfileList = useAppSelector(state => state.userProfile.entities); + const loading = useAppSelector(state => state.userProfile.loading); + const links = useAppSelector(state => state.userProfile.links); + const updateSuccess = useAppSelector(state => state.userProfile.updateSuccess); + + const getAllEntities = () => { + dispatch( + getEntities({ + page: paginationState.activePage - 1, + size: paginationState.itemsPerPage, + sort: `${paginationState.sort},${paginationState.order}`, + }), + ); + }; + + const resetAll = () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + }); + dispatch(getEntities({})); + }; + + useEffect(() => { + resetAll(); + }, []); + + useEffect(() => { + if (updateSuccess) { + resetAll(); + } + }, [updateSuccess]); + + useEffect(() => { + getAllEntities(); + }, [paginationState.activePage]); + + const handleLoadMore = () => { + if ((window as any).pageYOffset > 0) { + setPaginationState({ + ...paginationState, + activePage: paginationState.activePage + 1, + }); + } + }; + + useEffect(() => { + if (sorting) { + getAllEntities(); + setSorting(false); + } + }, [sorting]); + + const sort = p => () => { + dispatch(reset()); + setPaginationState({ + ...paginationState, + activePage: 1, + order: paginationState.order === ASC ? DESC : ASC, + sort: p, + }); + setSorting(true); + }; + + const handleSyncList = () => { + resetAll(); + }; + + const getSortIconByFieldName = (fieldName: string) => { + const sortFieldName = paginationState.sort; + const order = paginationState.order; + if (sortFieldName !== fieldName) { + return faSort; + } else { + return order === ASC ? faSortUp : faSortDown; + } + }; + + return ( + ++ + ); +}; + +export default UserProfile; diff --git a/src/main/webapp/app/shared/model/activity-invite.model.ts b/src/main/webapp/app/shared/model/activity-invite.model.ts new file mode 100644 index 0000000..5bdc456 --- /dev/null +++ b/src/main/webapp/app/shared/model/activity-invite.model.ts @@ -0,0 +1,20 @@ +import dayjs from 'dayjs'; +import { IActivity } from 'app/shared/model/activity.model'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { ICodeTables } from 'app/shared/model/code-tables.model'; + +export interface IActivityInvite { + id?: number; + willParticipate?: boolean | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + activity?: IActivity | null; + inviteeProfile?: IUserProfile | null; + status?: ICodeTables | null; +} + +export const defaultValue: Readonly+ User Profiles +
++ + +++ Create a new User Profile + + +} + > + {userProfileList && userProfileList.length > 0 ? ( +Loading ... + +
+ ) : ( + !loading &&+ + + + {userProfileList.map((userProfile, i) => ( ++ ID ++ + Nickname ++ + Job Role ++ + About Me ++ + Profile Picture ++ + Created By ++ + Created Date ++ + Last Modified By ++ + Last Modified Date ++ + User ++ + + + ))} + ++ + +{userProfile.nickname} +{userProfile.jobRole} +{userProfile.aboutMe} +{userProfile.profilePicture} +{userProfile.createdBy} ++ {userProfile.createdDate ? +: null} + {userProfile.lastModifiedBy} ++ {userProfile.lastModifiedDate ? ( + ++ ) : null} + {userProfile.user ? userProfile.user.login : ''} ++ ++ + + ++No User Profiles found+ )} + += { + willParticipate: false, +}; diff --git a/src/main/webapp/app/shared/model/activity.model.ts b/src/main/webapp/app/shared/model/activity.model.ts new file mode 100644 index 0000000..0891c3a --- /dev/null +++ b/src/main/webapp/app/shared/model/activity.model.ts @@ -0,0 +1,19 @@ +import dayjs from 'dayjs'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { ISkill } from 'app/shared/model/skill.model'; + +export interface IActivity { + id?: number; + activityTime?: dayjs.Dayjs; + duration?: number | null; + venue?: string | null; + details?: string | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + creatorProfile?: IUserProfile | null; + skill?: ISkill | null; +} + +export const defaultValue: Readonly = {}; diff --git a/src/main/webapp/app/shared/model/code-tables.model.ts b/src/main/webapp/app/shared/model/code-tables.model.ts new file mode 100644 index 0000000..a80fc24 --- /dev/null +++ b/src/main/webapp/app/shared/model/code-tables.model.ts @@ -0,0 +1,14 @@ +import dayjs from 'dayjs'; + +export interface ICodeTables { + id?: number; + category?: string | null; + codeKey?: string | null; + codeValue?: string | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; +} + +export const defaultValue: Readonly = {}; diff --git a/src/main/webapp/app/shared/model/message.model.ts b/src/main/webapp/app/shared/model/message.model.ts new file mode 100644 index 0000000..201fc2e --- /dev/null +++ b/src/main/webapp/app/shared/model/message.model.ts @@ -0,0 +1,19 @@ +import dayjs from 'dayjs'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; + +export interface IMessage { + id?: number; + content?: string; + sentAt?: dayjs.Dayjs; + isDeleted?: boolean | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + senderProfile?: IUserProfile | null; + receiverProfile?: IUserProfile | null; +} + +export const defaultValue: Readonly = { + isDeleted: false, +}; diff --git a/src/main/webapp/app/shared/model/notification.model.ts b/src/main/webapp/app/shared/model/notification.model.ts new file mode 100644 index 0000000..c5391e3 --- /dev/null +++ b/src/main/webapp/app/shared/model/notification.model.ts @@ -0,0 +1,20 @@ +import dayjs from 'dayjs'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; +import { ICodeTables } from 'app/shared/model/code-tables.model'; + +export interface INotification { + id?: number; + notificationRefId?: string | null; + content?: string | null; + isRead?: boolean | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + userProfile?: IUserProfile | null; + type?: ICodeTables | null; +} + +export const defaultValue: Readonly = { + isRead: false, +}; diff --git a/src/main/webapp/app/shared/model/skill.model.ts b/src/main/webapp/app/shared/model/skill.model.ts new file mode 100644 index 0000000..6dd348c --- /dev/null +++ b/src/main/webapp/app/shared/model/skill.model.ts @@ -0,0 +1,16 @@ +import dayjs from 'dayjs'; +import { IUserProfile } from 'app/shared/model/user-profile.model'; + +export interface ISkill { + id?: number; + skillName?: string; + individualSkillDesc?: string | null; + yearsOfExp?: number; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + userProfile?: IUserProfile | null; +} + +export const defaultValue: Readonly = {}; diff --git a/src/main/webapp/app/shared/model/user-profile.model.ts b/src/main/webapp/app/shared/model/user-profile.model.ts new file mode 100644 index 0000000..2e9eed8 --- /dev/null +++ b/src/main/webapp/app/shared/model/user-profile.model.ts @@ -0,0 +1,17 @@ +import dayjs from 'dayjs'; +import { IUser } from 'app/shared/model/user.model'; + +export interface IUserProfile { + id?: number; + nickname?: string | null; + jobRole?: string | null; + aboutMe?: string | null; + profilePicture?: string | null; + createdBy?: string; + createdDate?: dayjs.Dayjs; + lastModifiedBy?: string; + lastModifiedDate?: dayjs.Dayjs; + user?: IUser; +} + +export const defaultValue: Readonly = {}; diff --git a/src/test/java/com/teamsixnus/scaleup/TechnicalStructureTest.java b/src/test/java/com/teamsixnus/scaleup/TechnicalStructureTest.java index d57710a..eaf4439 100644 --- a/src/test/java/com/teamsixnus/scaleup/TechnicalStructureTest.java +++ b/src/test/java/com/teamsixnus/scaleup/TechnicalStructureTest.java @@ -2,8 +2,12 @@ import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue; import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.type; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; +import com.teamsixnus.scaleup.audit.EntityAuditEventListener; +import com.teamsixnus.scaleup.domain.AbstractAuditingEntity; import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; @@ -30,6 +34,8 @@ class TechnicalStructureTest { .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config") .whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config") + .ignoreDependency(resideInAPackage("com.teamsixnus.scaleup.audit"), alwaysTrue()) + .ignoreDependency(type(AbstractAuditingEntity.class), type(EntityAuditEventListener.class)) .ignoreDependency(belongToAnyOf(ScaleupApp.class), alwaysTrue()) .ignoreDependency(alwaysTrue(), belongToAnyOf( com.teamsixnus.scaleup.config.Constants.class, diff --git a/src/test/java/com/teamsixnus/scaleup/audit/TestEntityAuditEventWriter.java b/src/test/java/com/teamsixnus/scaleup/audit/TestEntityAuditEventWriter.java new file mode 100644 index 0000000..aee450f --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/audit/TestEntityAuditEventWriter.java @@ -0,0 +1,13 @@ +package com.teamsixnus.scaleup.audit; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TestEntityAuditEventWriter { + + @Bean + EntityAuditEventWriter entityAuditEventWriter() { + return (target, action) -> {}; + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityAsserts.java new file mode 100644 index 0000000..8014809 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityAsserts.java @@ -0,0 +1,70 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ActivityAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityAllPropertiesEquals(Activity expected, Activity actual) { + assertActivityAutoGeneratedPropertiesEquals(expected, actual); + assertActivityAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityAllUpdatablePropertiesEquals(Activity expected, Activity actual) { + assertActivityUpdatableFieldsEquals(expected, actual); + assertActivityUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityAutoGeneratedPropertiesEquals(Activity expected, Activity actual) { + assertThat(expected) + .as("Verify Activity auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityUpdatableFieldsEquals(Activity expected, Activity actual) { + assertThat(expected) + .as("Verify Activity relevant properties") + .satisfies(e -> assertThat(e.getActivityTime()).as("check activityTime").isEqualTo(actual.getActivityTime())) + .satisfies(e -> assertThat(e.getDuration()).as("check duration").isEqualTo(actual.getDuration())) + .satisfies(e -> assertThat(e.getVenue()).as("check venue").isEqualTo(actual.getVenue())) + .satisfies(e -> assertThat(e.getDetails()).as("check details").isEqualTo(actual.getDetails())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityUpdatableRelationshipsEquals(Activity expected, Activity actual) { + assertThat(expected) + .as("Verify Activity relationships") + .satisfies(e -> assertThat(e.getCreatorProfile()).as("check creatorProfile").isEqualTo(actual.getCreatorProfile())) + .satisfies(e -> assertThat(e.getSkill()).as("check skill").isEqualTo(actual.getSkill())); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteAsserts.java new file mode 100644 index 0000000..4ed2497 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteAsserts.java @@ -0,0 +1,68 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ActivityInviteAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityInviteAllPropertiesEquals(ActivityInvite expected, ActivityInvite actual) { + assertActivityInviteAutoGeneratedPropertiesEquals(expected, actual); + assertActivityInviteAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityInviteAllUpdatablePropertiesEquals(ActivityInvite expected, ActivityInvite actual) { + assertActivityInviteUpdatableFieldsEquals(expected, actual); + assertActivityInviteUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityInviteAutoGeneratedPropertiesEquals(ActivityInvite expected, ActivityInvite actual) { + assertThat(expected) + .as("Verify ActivityInvite auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityInviteUpdatableFieldsEquals(ActivityInvite expected, ActivityInvite actual) { + assertThat(expected) + .as("Verify ActivityInvite relevant properties") + .satisfies(e -> assertThat(e.getWillParticipate()).as("check willParticipate").isEqualTo(actual.getWillParticipate())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertActivityInviteUpdatableRelationshipsEquals(ActivityInvite expected, ActivityInvite actual) { + assertThat(expected) + .as("Verify ActivityInvite relationships") + .satisfies(e -> assertThat(e.getActivity()).as("check activity").isEqualTo(actual.getActivity())) + .satisfies(e -> assertThat(e.getInviteeProfile()).as("check inviteeProfile").isEqualTo(actual.getInviteeProfile())) + .satisfies(e -> assertThat(e.getStatus()).as("check status").isEqualTo(actual.getStatus())); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTest.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTest.java new file mode 100644 index 0000000..fc4f95b --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTest.java @@ -0,0 +1,63 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.ActivityInviteTestSamples.*; +import static com.teamsixnus.scaleup.domain.ActivityTestSamples.*; +import static com.teamsixnus.scaleup.domain.CodeTablesTestSamples.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class ActivityInviteTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(ActivityInvite.class); + ActivityInvite activityInvite1 = getActivityInviteSample1(); + ActivityInvite activityInvite2 = new ActivityInvite(); + assertThat(activityInvite1).isNotEqualTo(activityInvite2); + + activityInvite2.setId(activityInvite1.getId()); + assertThat(activityInvite1).isEqualTo(activityInvite2); + + activityInvite2 = getActivityInviteSample2(); + assertThat(activityInvite1).isNotEqualTo(activityInvite2); + } + + @Test + void activityTest() { + ActivityInvite activityInvite = getActivityInviteRandomSampleGenerator(); + Activity activityBack = getActivityRandomSampleGenerator(); + + activityInvite.setActivity(activityBack); + assertThat(activityInvite.getActivity()).isEqualTo(activityBack); + + activityInvite.activity(null); + assertThat(activityInvite.getActivity()).isNull(); + } + + @Test + void inviteeProfileTest() { + ActivityInvite activityInvite = getActivityInviteRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + activityInvite.setInviteeProfile(userProfileBack); + assertThat(activityInvite.getInviteeProfile()).isEqualTo(userProfileBack); + + activityInvite.inviteeProfile(null); + assertThat(activityInvite.getInviteeProfile()).isNull(); + } + + @Test + void statusTest() { + ActivityInvite activityInvite = getActivityInviteRandomSampleGenerator(); + CodeTables codeTablesBack = getCodeTablesRandomSampleGenerator(); + + activityInvite.setStatus(codeTablesBack); + assertThat(activityInvite.getStatus()).isEqualTo(codeTablesBack); + + activityInvite.status(null); + assertThat(activityInvite.getStatus()).isNull(); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTestSamples.java new file mode 100644 index 0000000..a49e866 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityInviteTestSamples.java @@ -0,0 +1,26 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +public class ActivityInviteTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + public static ActivityInvite getActivityInviteSample1() { + return new ActivityInvite().id(1L).createdBy("createdBy1").lastModifiedBy("lastModifiedBy1"); + } + + public static ActivityInvite getActivityInviteSample2() { + return new ActivityInvite().id(2L).createdBy("createdBy2").lastModifiedBy("lastModifiedBy2"); + } + + public static ActivityInvite getActivityInviteRandomSampleGenerator() { + return new ActivityInvite() + .id(longCount.incrementAndGet()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityTest.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityTest.java new file mode 100644 index 0000000..f0f004b --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityTest.java @@ -0,0 +1,50 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.ActivityTestSamples.*; +import static com.teamsixnus.scaleup.domain.SkillTestSamples.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class ActivityTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Activity.class); + Activity activity1 = getActivitySample1(); + Activity activity2 = new Activity(); + assertThat(activity1).isNotEqualTo(activity2); + + activity2.setId(activity1.getId()); + assertThat(activity1).isEqualTo(activity2); + + activity2 = getActivitySample2(); + assertThat(activity1).isNotEqualTo(activity2); + } + + @Test + void creatorProfileTest() { + Activity activity = getActivityRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + activity.setCreatorProfile(userProfileBack); + assertThat(activity.getCreatorProfile()).isEqualTo(userProfileBack); + + activity.creatorProfile(null); + assertThat(activity.getCreatorProfile()).isNull(); + } + + @Test + void skillTest() { + Activity activity = getActivityRandomSampleGenerator(); + Skill skillBack = getSkillRandomSampleGenerator(); + + activity.setSkill(skillBack); + assertThat(activity.getSkill()).isEqualTo(skillBack); + + activity.skill(null); + assertThat(activity.getSkill()).isNull(); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/ActivityTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/ActivityTestSamples.java new file mode 100644 index 0000000..936d23d --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/ActivityTestSamples.java @@ -0,0 +1,30 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +public class ActivityTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + private static final AtomicInteger intCount = new AtomicInteger(random.nextInt() + (2 * Short.MAX_VALUE)); + + public static Activity getActivitySample1() { + return new Activity().id(1L).duration(1).venue("venue1").createdBy("createdBy1").lastModifiedBy("lastModifiedBy1"); + } + + public static Activity getActivitySample2() { + return new Activity().id(2L).duration(2).venue("venue2").createdBy("createdBy2").lastModifiedBy("lastModifiedBy2"); + } + + public static Activity getActivityRandomSampleGenerator() { + return new Activity() + .id(longCount.incrementAndGet()) + .duration(intCount.incrementAndGet()) + .venue(UUID.randomUUID().toString()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesAsserts.java new file mode 100644 index 0000000..2f4fd97 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesAsserts.java @@ -0,0 +1,64 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CodeTablesAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertCodeTablesAllPropertiesEquals(CodeTables expected, CodeTables actual) { + assertCodeTablesAutoGeneratedPropertiesEquals(expected, actual); + assertCodeTablesAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertCodeTablesAllUpdatablePropertiesEquals(CodeTables expected, CodeTables actual) { + assertCodeTablesUpdatableFieldsEquals(expected, actual); + assertCodeTablesUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertCodeTablesAutoGeneratedPropertiesEquals(CodeTables expected, CodeTables actual) { + assertThat(expected) + .as("Verify CodeTables auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertCodeTablesUpdatableFieldsEquals(CodeTables expected, CodeTables actual) { + assertThat(expected) + .as("Verify CodeTables relevant properties") + .satisfies(e -> assertThat(e.getCategory()).as("check category").isEqualTo(actual.getCategory())) + .satisfies(e -> assertThat(e.getCodeKey()).as("check codeKey").isEqualTo(actual.getCodeKey())) + .satisfies(e -> assertThat(e.getCodeValue()).as("check codeValue").isEqualTo(actual.getCodeValue())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertCodeTablesUpdatableRelationshipsEquals(CodeTables expected, CodeTables actual) {} +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTest.java b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTest.java new file mode 100644 index 0000000..8c3b421 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.CodeTablesTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class CodeTablesTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(CodeTables.class); + CodeTables codeTables1 = getCodeTablesSample1(); + CodeTables codeTables2 = new CodeTables(); + assertThat(codeTables1).isNotEqualTo(codeTables2); + + codeTables2.setId(codeTables1.getId()); + assertThat(codeTables1).isEqualTo(codeTables2); + + codeTables2 = getCodeTablesSample2(); + assertThat(codeTables1).isNotEqualTo(codeTables2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTestSamples.java new file mode 100644 index 0000000..9d41a72 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/CodeTablesTestSamples.java @@ -0,0 +1,41 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +public class CodeTablesTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + public static CodeTables getCodeTablesSample1() { + return new CodeTables() + .id(1L) + .category("category1") + .codeKey("codeKey1") + .codeValue("codeValue1") + .createdBy("createdBy1") + .lastModifiedBy("lastModifiedBy1"); + } + + public static CodeTables getCodeTablesSample2() { + return new CodeTables() + .id(2L) + .category("category2") + .codeKey("codeKey2") + .codeValue("codeValue2") + .createdBy("createdBy2") + .lastModifiedBy("lastModifiedBy2"); + } + + public static CodeTables getCodeTablesRandomSampleGenerator() { + return new CodeTables() + .id(longCount.incrementAndGet()) + .category(UUID.randomUUID().toString()) + .codeKey(UUID.randomUUID().toString()) + .codeValue(UUID.randomUUID().toString()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/MessageAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/MessageAsserts.java new file mode 100644 index 0000000..36fbae7 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/MessageAsserts.java @@ -0,0 +1,69 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MessageAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertMessageAllPropertiesEquals(Message expected, Message actual) { + assertMessageAutoGeneratedPropertiesEquals(expected, actual); + assertMessageAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertMessageAllUpdatablePropertiesEquals(Message expected, Message actual) { + assertMessageUpdatableFieldsEquals(expected, actual); + assertMessageUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertMessageAutoGeneratedPropertiesEquals(Message expected, Message actual) { + assertThat(expected) + .as("Verify Message auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertMessageUpdatableFieldsEquals(Message expected, Message actual) { + assertThat(expected) + .as("Verify Message relevant properties") + .satisfies(e -> assertThat(e.getContent()).as("check content").isEqualTo(actual.getContent())) + .satisfies(e -> assertThat(e.getSentAt()).as("check sentAt").isEqualTo(actual.getSentAt())) + .satisfies(e -> assertThat(e.getIsDeleted()).as("check isDeleted").isEqualTo(actual.getIsDeleted())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertMessageUpdatableRelationshipsEquals(Message expected, Message actual) { + assertThat(expected) + .as("Verify Message relationships") + .satisfies(e -> assertThat(e.getSenderProfile()).as("check senderProfile").isEqualTo(actual.getSenderProfile())) + .satisfies(e -> assertThat(e.getReceiverProfile()).as("check receiverProfile").isEqualTo(actual.getReceiverProfile())); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/MessageTest.java b/src/test/java/com/teamsixnus/scaleup/domain/MessageTest.java new file mode 100644 index 0000000..2dd95d7 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/MessageTest.java @@ -0,0 +1,49 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.MessageTestSamples.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class MessageTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Message.class); + Message message1 = getMessageSample1(); + Message message2 = new Message(); + assertThat(message1).isNotEqualTo(message2); + + message2.setId(message1.getId()); + assertThat(message1).isEqualTo(message2); + + message2 = getMessageSample2(); + assertThat(message1).isNotEqualTo(message2); + } + + @Test + void senderProfileTest() { + Message message = getMessageRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + message.setSenderProfile(userProfileBack); + assertThat(message.getSenderProfile()).isEqualTo(userProfileBack); + + message.senderProfile(null); + assertThat(message.getSenderProfile()).isNull(); + } + + @Test + void receiverProfileTest() { + Message message = getMessageRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + message.setReceiverProfile(userProfileBack); + assertThat(message.getReceiverProfile()).isEqualTo(userProfileBack); + + message.receiverProfile(null); + assertThat(message.getReceiverProfile()).isNull(); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/MessageTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/MessageTestSamples.java new file mode 100644 index 0000000..eff438a --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/MessageTestSamples.java @@ -0,0 +1,26 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +public class MessageTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + public static Message getMessageSample1() { + return new Message().id(1L).createdBy("createdBy1").lastModifiedBy("lastModifiedBy1"); + } + + public static Message getMessageSample2() { + return new Message().id(2L).createdBy("createdBy2").lastModifiedBy("lastModifiedBy2"); + } + + public static Message getMessageRandomSampleGenerator() { + return new Message() + .id(longCount.incrementAndGet()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/NotificationAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/NotificationAsserts.java new file mode 100644 index 0000000..22e224a --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/NotificationAsserts.java @@ -0,0 +1,69 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class NotificationAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertNotificationAllPropertiesEquals(Notification expected, Notification actual) { + assertNotificationAutoGeneratedPropertiesEquals(expected, actual); + assertNotificationAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertNotificationAllUpdatablePropertiesEquals(Notification expected, Notification actual) { + assertNotificationUpdatableFieldsEquals(expected, actual); + assertNotificationUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertNotificationAutoGeneratedPropertiesEquals(Notification expected, Notification actual) { + assertThat(expected) + .as("Verify Notification auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertNotificationUpdatableFieldsEquals(Notification expected, Notification actual) { + assertThat(expected) + .as("Verify Notification relevant properties") + .satisfies(e -> assertThat(e.getNotificationRefId()).as("check notificationRefId").isEqualTo(actual.getNotificationRefId())) + .satisfies(e -> assertThat(e.getContent()).as("check content").isEqualTo(actual.getContent())) + .satisfies(e -> assertThat(e.getIsRead()).as("check isRead").isEqualTo(actual.getIsRead())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertNotificationUpdatableRelationshipsEquals(Notification expected, Notification actual) { + assertThat(expected) + .as("Verify Notification relationships") + .satisfies(e -> assertThat(e.getUserProfile()).as("check userProfile").isEqualTo(actual.getUserProfile())) + .satisfies(e -> assertThat(e.getType()).as("check type").isEqualTo(actual.getType())); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/NotificationTest.java b/src/test/java/com/teamsixnus/scaleup/domain/NotificationTest.java new file mode 100644 index 0000000..554a23f --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/NotificationTest.java @@ -0,0 +1,50 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.CodeTablesTestSamples.*; +import static com.teamsixnus.scaleup.domain.NotificationTestSamples.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class NotificationTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Notification.class); + Notification notification1 = getNotificationSample1(); + Notification notification2 = new Notification(); + assertThat(notification1).isNotEqualTo(notification2); + + notification2.setId(notification1.getId()); + assertThat(notification1).isEqualTo(notification2); + + notification2 = getNotificationSample2(); + assertThat(notification1).isNotEqualTo(notification2); + } + + @Test + void userProfileTest() { + Notification notification = getNotificationRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + notification.setUserProfile(userProfileBack); + assertThat(notification.getUserProfile()).isEqualTo(userProfileBack); + + notification.userProfile(null); + assertThat(notification.getUserProfile()).isNull(); + } + + @Test + void typeTest() { + Notification notification = getNotificationRandomSampleGenerator(); + CodeTables codeTablesBack = getCodeTablesRandomSampleGenerator(); + + notification.setType(codeTablesBack); + assertThat(notification.getType()).isEqualTo(codeTablesBack); + + notification.type(null); + assertThat(notification.getType()).isNull(); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/NotificationTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/NotificationTestSamples.java new file mode 100644 index 0000000..a029dc6 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/NotificationTestSamples.java @@ -0,0 +1,35 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +public class NotificationTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + public static Notification getNotificationSample1() { + return new Notification() + .id(1L) + .notificationRefId(UUID.fromString("23d8dc04-a48b-45d9-a01d-4b728f0ad4aa")) + .createdBy("createdBy1") + .lastModifiedBy("lastModifiedBy1"); + } + + public static Notification getNotificationSample2() { + return new Notification() + .id(2L) + .notificationRefId(UUID.fromString("ad79f240-3727-46c3-b89f-2cf6ebd74367")) + .createdBy("createdBy2") + .lastModifiedBy("lastModifiedBy2"); + } + + public static Notification getNotificationRandomSampleGenerator() { + return new Notification() + .id(longCount.incrementAndGet()) + .notificationRefId(UUID.randomUUID()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/SkillAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/SkillAsserts.java new file mode 100644 index 0000000..d3fa33c --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/SkillAsserts.java @@ -0,0 +1,70 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SkillAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertSkillAllPropertiesEquals(Skill expected, Skill actual) { + assertSkillAutoGeneratedPropertiesEquals(expected, actual); + assertSkillAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertSkillAllUpdatablePropertiesEquals(Skill expected, Skill actual) { + assertSkillUpdatableFieldsEquals(expected, actual); + assertSkillUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertSkillAutoGeneratedPropertiesEquals(Skill expected, Skill actual) { + assertThat(expected) + .as("Verify Skill auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertSkillUpdatableFieldsEquals(Skill expected, Skill actual) { + assertThat(expected) + .as("Verify Skill relevant properties") + .satisfies(e -> assertThat(e.getSkillName()).as("check skillName").isEqualTo(actual.getSkillName())) + .satisfies( + e -> assertThat(e.getIndividualSkillDesc()).as("check individualSkillDesc").isEqualTo(actual.getIndividualSkillDesc()) + ) + .satisfies(e -> assertThat(e.getYearsOfExp()).as("check yearsOfExp").isEqualTo(actual.getYearsOfExp())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertSkillUpdatableRelationshipsEquals(Skill expected, Skill actual) { + assertThat(expected) + .as("Verify Skill relationships") + .satisfies(e -> assertThat(e.getUserProfile()).as("check userProfile").isEqualTo(actual.getUserProfile())); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/SkillTest.java b/src/test/java/com/teamsixnus/scaleup/domain/SkillTest.java new file mode 100644 index 0000000..ee41bab --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/SkillTest.java @@ -0,0 +1,37 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.SkillTestSamples.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class SkillTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Skill.class); + Skill skill1 = getSkillSample1(); + Skill skill2 = new Skill(); + assertThat(skill1).isNotEqualTo(skill2); + + skill2.setId(skill1.getId()); + assertThat(skill1).isEqualTo(skill2); + + skill2 = getSkillSample2(); + assertThat(skill1).isNotEqualTo(skill2); + } + + @Test + void userProfileTest() { + Skill skill = getSkillRandomSampleGenerator(); + UserProfile userProfileBack = getUserProfileRandomSampleGenerator(); + + skill.setUserProfile(userProfileBack); + assertThat(skill.getUserProfile()).isEqualTo(userProfileBack); + + skill.userProfile(null); + assertThat(skill.getUserProfile()).isNull(); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/SkillTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/SkillTestSamples.java new file mode 100644 index 0000000..ed2820d --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/SkillTestSamples.java @@ -0,0 +1,43 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +public class SkillTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + private static final AtomicInteger intCount = new AtomicInteger(random.nextInt() + (2 * Short.MAX_VALUE)); + + public static Skill getSkillSample1() { + return new Skill() + .id(1L) + .skillName("skillName1") + .individualSkillDesc("individualSkillDesc1") + .yearsOfExp(1) + .createdBy("createdBy1") + .lastModifiedBy("lastModifiedBy1"); + } + + public static Skill getSkillSample2() { + return new Skill() + .id(2L) + .skillName("skillName2") + .individualSkillDesc("individualSkillDesc2") + .yearsOfExp(2) + .createdBy("createdBy2") + .lastModifiedBy("lastModifiedBy2"); + } + + public static Skill getSkillRandomSampleGenerator() { + return new Skill() + .id(longCount.incrementAndGet()) + .skillName(UUID.randomUUID().toString()) + .individualSkillDesc(UUID.randomUUID().toString()) + .yearsOfExp(intCount.incrementAndGet()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/UserProfileAsserts.java b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileAsserts.java new file mode 100644 index 0000000..bfd87a2 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileAsserts.java @@ -0,0 +1,65 @@ +package com.teamsixnus.scaleup.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserProfileAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertUserProfileAllPropertiesEquals(UserProfile expected, UserProfile actual) { + assertUserProfileAutoGeneratedPropertiesEquals(expected, actual); + assertUserProfileAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertUserProfileAllUpdatablePropertiesEquals(UserProfile expected, UserProfile actual) { + assertUserProfileUpdatableFieldsEquals(expected, actual); + assertUserProfileUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertUserProfileAutoGeneratedPropertiesEquals(UserProfile expected, UserProfile actual) { + assertThat(expected) + .as("Verify UserProfile auto generated properties") + .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())) + .satisfies(e -> assertThat(e.getCreatedBy()).as("check createdBy").isEqualTo(actual.getCreatedBy())) + .satisfies(e -> assertThat(e.getCreatedDate()).as("check createdDate").isEqualTo(actual.getCreatedDate())); + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertUserProfileUpdatableFieldsEquals(UserProfile expected, UserProfile actual) { + assertThat(expected) + .as("Verify UserProfile relevant properties") + .satisfies(e -> assertThat(e.getNickname()).as("check nickname").isEqualTo(actual.getNickname())) + .satisfies(e -> assertThat(e.getJobRole()).as("check jobRole").isEqualTo(actual.getJobRole())) + .satisfies(e -> assertThat(e.getAboutMe()).as("check aboutMe").isEqualTo(actual.getAboutMe())) + .satisfies(e -> assertThat(e.getProfilePicture()).as("check profilePicture").isEqualTo(actual.getProfilePicture())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertUserProfileUpdatableRelationshipsEquals(UserProfile expected, UserProfile actual) {} +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTest.java b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTest.java new file mode 100644 index 0000000..6da7da0 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.domain; + +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class UserProfileTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(UserProfile.class); + UserProfile userProfile1 = getUserProfileSample1(); + UserProfile userProfile2 = new UserProfile(); + assertThat(userProfile1).isNotEqualTo(userProfile2); + + userProfile2.setId(userProfile1.getId()); + assertThat(userProfile1).isEqualTo(userProfile2); + + userProfile2 = getUserProfileSample2(); + assertThat(userProfile1).isNotEqualTo(userProfile2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTestSamples.java b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTestSamples.java new file mode 100644 index 0000000..e6f4f74 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/domain/UserProfileTestSamples.java @@ -0,0 +1,44 @@ +package com.teamsixnus.scaleup.domain; + +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +public class UserProfileTestSamples { + + private static final Random random = new Random(); + private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + public static UserProfile getUserProfileSample1() { + return new UserProfile() + .id(1L) + .nickname("nickname1") + .jobRole("jobRole1") + .aboutMe("aboutMe1") + .profilePicture("profilePicture1") + .createdBy("createdBy1") + .lastModifiedBy("lastModifiedBy1"); + } + + public static UserProfile getUserProfileSample2() { + return new UserProfile() + .id(2L) + .nickname("nickname2") + .jobRole("jobRole2") + .aboutMe("aboutMe2") + .profilePicture("profilePicture2") + .createdBy("createdBy2") + .lastModifiedBy("lastModifiedBy2"); + } + + public static UserProfile getUserProfileRandomSampleGenerator() { + return new UserProfile() + .id(longCount.incrementAndGet()) + .nickname(UUID.randomUUID().toString()) + .jobRole(UUID.randomUUID().toString()) + .aboutMe(UUID.randomUUID().toString()) + .profilePicture(UUID.randomUUID().toString()) + .createdBy(UUID.randomUUID().toString()) + .lastModifiedBy(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/MailServiceIT.java b/src/test/java/com/teamsixnus/scaleup/service/MailServiceIT.java index 1336494..1c98438 100644 --- a/src/test/java/com/teamsixnus/scaleup/service/MailServiceIT.java +++ b/src/test/java/com/teamsixnus/scaleup/service/MailServiceIT.java @@ -69,7 +69,7 @@ void testSendEmail() throws Exception { MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent()).hasToString("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); @@ -82,7 +82,7 @@ void testSendHtmlEmail() throws Exception { MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent()).hasToString("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); @@ -99,7 +99,7 @@ void testSendMultipartEmail() throws Exception { part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos).hasToString("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); @@ -116,7 +116,7 @@ void testSendMultipartHtmlEmail() throws Exception { part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos).hasToString("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); @@ -133,7 +133,7 @@ void testSendEmailFromTemplate() throws Exception { MimeMessage message = messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("test title"); assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @@ -148,7 +148,7 @@ void testSendActivationEmail() throws Exception { verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @@ -163,7 +163,7 @@ void testCreationEmail() throws Exception { verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @@ -178,7 +178,7 @@ void testSendPasswordResetMail() throws Exception { verify(javaMailSender).send(messageCaptor.capture()); MimeMessage message = messageCaptor.getValue(); assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); - assertThat(message.getFrom()[0]).hasToString("MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityDTOTest.java new file mode 100644 index 0000000..927e316 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class ActivityDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(ActivityDTO.class); + ActivityDTO activityDTO1 = new ActivityDTO(); + activityDTO1.setId(1L); + ActivityDTO activityDTO2 = new ActivityDTO(); + assertThat(activityDTO1).isNotEqualTo(activityDTO2); + activityDTO2.setId(activityDTO1.getId()); + assertThat(activityDTO1).isEqualTo(activityDTO2); + activityDTO2.setId(2L); + assertThat(activityDTO1).isNotEqualTo(activityDTO2); + activityDTO1.setId(null); + assertThat(activityDTO1).isNotEqualTo(activityDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityInviteDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityInviteDTOTest.java new file mode 100644 index 0000000..9606822 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/ActivityInviteDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class ActivityInviteDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(ActivityInviteDTO.class); + ActivityInviteDTO activityInviteDTO1 = new ActivityInviteDTO(); + activityInviteDTO1.setId(1L); + ActivityInviteDTO activityInviteDTO2 = new ActivityInviteDTO(); + assertThat(activityInviteDTO1).isNotEqualTo(activityInviteDTO2); + activityInviteDTO2.setId(activityInviteDTO1.getId()); + assertThat(activityInviteDTO1).isEqualTo(activityInviteDTO2); + activityInviteDTO2.setId(2L); + assertThat(activityInviteDTO1).isNotEqualTo(activityInviteDTO2); + activityInviteDTO1.setId(null); + assertThat(activityInviteDTO1).isNotEqualTo(activityInviteDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/CodeTablesDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/CodeTablesDTOTest.java new file mode 100644 index 0000000..aaa60aa --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/CodeTablesDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class CodeTablesDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(CodeTablesDTO.class); + CodeTablesDTO codeTablesDTO1 = new CodeTablesDTO(); + codeTablesDTO1.setId(1L); + CodeTablesDTO codeTablesDTO2 = new CodeTablesDTO(); + assertThat(codeTablesDTO1).isNotEqualTo(codeTablesDTO2); + codeTablesDTO2.setId(codeTablesDTO1.getId()); + assertThat(codeTablesDTO1).isEqualTo(codeTablesDTO2); + codeTablesDTO2.setId(2L); + assertThat(codeTablesDTO1).isNotEqualTo(codeTablesDTO2); + codeTablesDTO1.setId(null); + assertThat(codeTablesDTO1).isNotEqualTo(codeTablesDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/MessageDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/MessageDTOTest.java new file mode 100644 index 0000000..9e5cb0d --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/MessageDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class MessageDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(MessageDTO.class); + MessageDTO messageDTO1 = new MessageDTO(); + messageDTO1.setId(1L); + MessageDTO messageDTO2 = new MessageDTO(); + assertThat(messageDTO1).isNotEqualTo(messageDTO2); + messageDTO2.setId(messageDTO1.getId()); + assertThat(messageDTO1).isEqualTo(messageDTO2); + messageDTO2.setId(2L); + assertThat(messageDTO1).isNotEqualTo(messageDTO2); + messageDTO1.setId(null); + assertThat(messageDTO1).isNotEqualTo(messageDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/NotificationDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/NotificationDTOTest.java new file mode 100644 index 0000000..428fb4b --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/NotificationDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class NotificationDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(NotificationDTO.class); + NotificationDTO notificationDTO1 = new NotificationDTO(); + notificationDTO1.setId(1L); + NotificationDTO notificationDTO2 = new NotificationDTO(); + assertThat(notificationDTO1).isNotEqualTo(notificationDTO2); + notificationDTO2.setId(notificationDTO1.getId()); + assertThat(notificationDTO1).isEqualTo(notificationDTO2); + notificationDTO2.setId(2L); + assertThat(notificationDTO1).isNotEqualTo(notificationDTO2); + notificationDTO1.setId(null); + assertThat(notificationDTO1).isNotEqualTo(notificationDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/SkillDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/SkillDTOTest.java new file mode 100644 index 0000000..36627b4 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/SkillDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class SkillDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(SkillDTO.class); + SkillDTO skillDTO1 = new SkillDTO(); + skillDTO1.setId(1L); + SkillDTO skillDTO2 = new SkillDTO(); + assertThat(skillDTO1).isNotEqualTo(skillDTO2); + skillDTO2.setId(skillDTO1.getId()); + assertThat(skillDTO1).isEqualTo(skillDTO2); + skillDTO2.setId(2L); + assertThat(skillDTO1).isNotEqualTo(skillDTO2); + skillDTO1.setId(null); + assertThat(skillDTO1).isNotEqualTo(skillDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/dto/UserProfileDTOTest.java b/src/test/java/com/teamsixnus/scaleup/service/dto/UserProfileDTOTest.java new file mode 100644 index 0000000..f890c84 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/dto/UserProfileDTOTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.dto; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.teamsixnus.scaleup.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class UserProfileDTOTest { + + @Test + void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(UserProfileDTO.class); + UserProfileDTO userProfileDTO1 = new UserProfileDTO(); + userProfileDTO1.setId(1L); + UserProfileDTO userProfileDTO2 = new UserProfileDTO(); + assertThat(userProfileDTO1).isNotEqualTo(userProfileDTO2); + userProfileDTO2.setId(userProfileDTO1.getId()); + assertThat(userProfileDTO1).isEqualTo(userProfileDTO2); + userProfileDTO2.setId(2L); + assertThat(userProfileDTO1).isNotEqualTo(userProfileDTO2); + userProfileDTO1.setId(null); + assertThat(userProfileDTO1).isNotEqualTo(userProfileDTO2); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityInviteMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityInviteMapperTest.java new file mode 100644 index 0000000..493cb49 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityInviteMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.ActivityInviteAsserts.*; +import static com.teamsixnus.scaleup.domain.ActivityInviteTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ActivityInviteMapperTest { + + private ActivityInviteMapper activityInviteMapper; + + @BeforeEach + void setUp() { + activityInviteMapper = new ActivityInviteMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getActivityInviteSample1(); + var actual = activityInviteMapper.toEntity(activityInviteMapper.toDto(expected)); + assertActivityInviteAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityMapperTest.java new file mode 100644 index 0000000..fe18f93 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/ActivityMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.ActivityAsserts.*; +import static com.teamsixnus.scaleup.domain.ActivityTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ActivityMapperTest { + + private ActivityMapper activityMapper; + + @BeforeEach + void setUp() { + activityMapper = new ActivityMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getActivitySample1(); + var actual = activityMapper.toEntity(activityMapper.toDto(expected)); + assertActivityAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/CodeTablesMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/CodeTablesMapperTest.java new file mode 100644 index 0000000..2ad856a --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/CodeTablesMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.CodeTablesAsserts.*; +import static com.teamsixnus.scaleup.domain.CodeTablesTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CodeTablesMapperTest { + + private CodeTablesMapper codeTablesMapper; + + @BeforeEach + void setUp() { + codeTablesMapper = new CodeTablesMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getCodeTablesSample1(); + var actual = codeTablesMapper.toEntity(codeTablesMapper.toDto(expected)); + assertCodeTablesAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/MessageMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/MessageMapperTest.java new file mode 100644 index 0000000..a850f01 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/MessageMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.MessageAsserts.*; +import static com.teamsixnus.scaleup.domain.MessageTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class MessageMapperTest { + + private MessageMapper messageMapper; + + @BeforeEach + void setUp() { + messageMapper = new MessageMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getMessageSample1(); + var actual = messageMapper.toEntity(messageMapper.toDto(expected)); + assertMessageAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/NotificationMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/NotificationMapperTest.java new file mode 100644 index 0000000..1b8e29f --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/NotificationMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.NotificationAsserts.*; +import static com.teamsixnus.scaleup.domain.NotificationTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class NotificationMapperTest { + + private NotificationMapper notificationMapper; + + @BeforeEach + void setUp() { + notificationMapper = new NotificationMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getNotificationSample1(); + var actual = notificationMapper.toEntity(notificationMapper.toDto(expected)); + assertNotificationAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/SkillMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/SkillMapperTest.java new file mode 100644 index 0000000..a6e5a7c --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/SkillMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.SkillAsserts.*; +import static com.teamsixnus.scaleup.domain.SkillTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SkillMapperTest { + + private SkillMapper skillMapper; + + @BeforeEach + void setUp() { + skillMapper = new SkillMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getSkillSample1(); + var actual = skillMapper.toEntity(skillMapper.toDto(expected)); + assertSkillAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/service/mapper/UserProfileMapperTest.java b/src/test/java/com/teamsixnus/scaleup/service/mapper/UserProfileMapperTest.java new file mode 100644 index 0000000..19edafb --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/service/mapper/UserProfileMapperTest.java @@ -0,0 +1,24 @@ +package com.teamsixnus.scaleup.service.mapper; + +import static com.teamsixnus.scaleup.domain.UserProfileAsserts.*; +import static com.teamsixnus.scaleup.domain.UserProfileTestSamples.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class UserProfileMapperTest { + + private UserProfileMapper userProfileMapper; + + @BeforeEach + void setUp() { + userProfileMapper = new UserProfileMapperImpl(); + } + + @Test + void shouldConvertToDtoAndBack() { + var expected = getUserProfileSample1(); + var actual = userProfileMapper.toEntity(userProfileMapper.toDto(expected)); + assertUserProfileAllPropertiesEquals(expected, actual); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityInviteResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityInviteResourceIT.java new file mode 100644 index 0000000..c0b762e --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityInviteResourceIT.java @@ -0,0 +1,434 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.ActivityInviteAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.ActivityInvite; +import com.teamsixnus.scaleup.repository.ActivityInviteRepository; +import com.teamsixnus.scaleup.service.dto.ActivityInviteDTO; +import com.teamsixnus.scaleup.service.mapper.ActivityInviteMapper; +import jakarta.persistence.EntityManager; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link ActivityInviteResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class ActivityInviteResourceIT { + + private static final Boolean DEFAULT_WILL_PARTICIPATE = false; + private static final Boolean UPDATED_WILL_PARTICIPATE = true; + + private static final String ENTITY_API_URL = "/api/activity-invites"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private ActivityInviteRepository activityInviteRepository; + + @Autowired + private ActivityInviteMapper activityInviteMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restActivityInviteMockMvc; + + private ActivityInvite activityInvite; + + private ActivityInvite insertedActivityInvite; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static ActivityInvite createEntity(EntityManager em) { + ActivityInvite activityInvite = new ActivityInvite().willParticipate(DEFAULT_WILL_PARTICIPATE); + return activityInvite; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static ActivityInvite createUpdatedEntity(EntityManager em) { + ActivityInvite activityInvite = new ActivityInvite().willParticipate(UPDATED_WILL_PARTICIPATE); + return activityInvite; + } + + @BeforeEach + public void initTest() { + activityInvite = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedActivityInvite != null) { + activityInviteRepository.delete(insertedActivityInvite); + insertedActivityInvite = null; + } + } + + @Test + @Transactional + void createActivityInvite() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + var returnedActivityInviteDTO = om.readValue( + restActivityInviteMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityInviteDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + ActivityInviteDTO.class + ); + + // Validate the ActivityInvite in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedActivityInvite = activityInviteMapper.toEntity(returnedActivityInviteDTO); + assertActivityInviteUpdatableFieldsEquals(returnedActivityInvite, getPersistedActivityInvite(returnedActivityInvite)); + + insertedActivityInvite = returnedActivityInvite; + } + + @Test + @Transactional + void createActivityInviteWithExistingId() throws Exception { + // Create the ActivityInvite with an existing ID + activityInvite.setId(1L); + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restActivityInviteMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityInviteDTO))) + .andExpect(status().isBadRequest()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void getAllActivityInvites() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + // Get all the activityInviteList + restActivityInviteMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(activityInvite.getId().intValue()))) + .andExpect(jsonPath("$.[*].willParticipate").value(hasItem(DEFAULT_WILL_PARTICIPATE.booleanValue()))); + } + + @Test + @Transactional + void getActivityInvite() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + // Get the activityInvite + restActivityInviteMockMvc + .perform(get(ENTITY_API_URL_ID, activityInvite.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(activityInvite.getId().intValue())) + .andExpect(jsonPath("$.willParticipate").value(DEFAULT_WILL_PARTICIPATE.booleanValue())); + } + + @Test + @Transactional + void getNonExistingActivityInvite() throws Exception { + // Get the activityInvite + restActivityInviteMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingActivityInvite() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activityInvite + ActivityInvite updatedActivityInvite = activityInviteRepository.findById(activityInvite.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedActivityInvite are not directly saved in db + em.detach(updatedActivityInvite); + updatedActivityInvite.willParticipate(UPDATED_WILL_PARTICIPATE); + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(updatedActivityInvite); + + restActivityInviteMockMvc + .perform( + put(ENTITY_API_URL_ID, activityInviteDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityInviteDTO)) + ) + .andExpect(status().isOk()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedActivityInviteToMatchAllProperties(updatedActivityInvite); + } + + @Test + @Transactional + void putNonExistingActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform( + put(ENTITY_API_URL_ID, activityInviteDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityInviteDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityInviteDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityInviteDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateActivityInviteWithPatch() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activityInvite using partial update + ActivityInvite partialUpdatedActivityInvite = new ActivityInvite(); + partialUpdatedActivityInvite.setId(activityInvite.getId()); + + partialUpdatedActivityInvite.willParticipate(UPDATED_WILL_PARTICIPATE); + + restActivityInviteMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedActivityInvite.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedActivityInvite)) + ) + .andExpect(status().isOk()); + + // Validate the ActivityInvite in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertActivityInviteUpdatableFieldsEquals( + createUpdateProxyForBean(partialUpdatedActivityInvite, activityInvite), + getPersistedActivityInvite(activityInvite) + ); + } + + @Test + @Transactional + void fullUpdateActivityInviteWithPatch() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activityInvite using partial update + ActivityInvite partialUpdatedActivityInvite = new ActivityInvite(); + partialUpdatedActivityInvite.setId(activityInvite.getId()); + + partialUpdatedActivityInvite.willParticipate(UPDATED_WILL_PARTICIPATE); + + restActivityInviteMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedActivityInvite.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedActivityInvite)) + ) + .andExpect(status().isOk()); + + // Validate the ActivityInvite in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertActivityInviteUpdatableFieldsEquals(partialUpdatedActivityInvite, getPersistedActivityInvite(partialUpdatedActivityInvite)); + } + + @Test + @Transactional + void patchNonExistingActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform( + patch(ENTITY_API_URL_ID, activityInviteDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(activityInviteDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(activityInviteDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamActivityInvite() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activityInvite.setId(longCount.incrementAndGet()); + + // Create the ActivityInvite + ActivityInviteDTO activityInviteDTO = activityInviteMapper.toDto(activityInvite); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityInviteMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(activityInviteDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the ActivityInvite in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteActivityInvite() throws Exception { + // Initialize the database + insertedActivityInvite = activityInviteRepository.saveAndFlush(activityInvite); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the activityInvite + restActivityInviteMockMvc + .perform(delete(ENTITY_API_URL_ID, activityInvite.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return activityInviteRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected ActivityInvite getPersistedActivityInvite(ActivityInvite activityInvite) { + return activityInviteRepository.findById(activityInvite.getId()).orElseThrow(); + } + + protected void assertPersistedActivityInviteToMatchAllProperties(ActivityInvite expectedActivityInvite) { + assertActivityInviteAllPropertiesEquals(expectedActivityInvite, getPersistedActivityInvite(expectedActivityInvite)); + } + + protected void assertPersistedActivityInviteToMatchUpdatableProperties(ActivityInvite expectedActivityInvite) { + assertActivityInviteAllUpdatablePropertiesEquals(expectedActivityInvite, getPersistedActivityInvite(expectedActivityInvite)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityResourceIT.java new file mode 100644 index 0000000..2042bde --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/ActivityResourceIT.java @@ -0,0 +1,473 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.ActivityAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.Activity; +import com.teamsixnus.scaleup.repository.ActivityRepository; +import com.teamsixnus.scaleup.service.dto.ActivityDTO; +import com.teamsixnus.scaleup.service.mapper.ActivityMapper; +import jakarta.persistence.EntityManager; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link ActivityResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class ActivityResourceIT { + + private static final Instant DEFAULT_ACTIVITY_TIME = Instant.ofEpochMilli(0L); + private static final Instant UPDATED_ACTIVITY_TIME = Instant.now().truncatedTo(ChronoUnit.MILLIS); + + private static final Integer DEFAULT_DURATION = 1; + private static final Integer UPDATED_DURATION = 2; + + private static final String DEFAULT_VENUE = "AAAAAAAAAA"; + private static final String UPDATED_VENUE = "BBBBBBBBBB"; + + private static final String DEFAULT_DETAILS = "AAAAAAAAAA"; + private static final String UPDATED_DETAILS = "BBBBBBBBBB"; + + private static final String ENTITY_API_URL = "/api/activities"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private ActivityRepository activityRepository; + + @Autowired + private ActivityMapper activityMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restActivityMockMvc; + + private Activity activity; + + private Activity insertedActivity; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Activity createEntity(EntityManager em) { + Activity activity = new Activity() + .activityTime(DEFAULT_ACTIVITY_TIME) + .duration(DEFAULT_DURATION) + .venue(DEFAULT_VENUE) + .details(DEFAULT_DETAILS); + return activity; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Activity createUpdatedEntity(EntityManager em) { + Activity activity = new Activity() + .activityTime(UPDATED_ACTIVITY_TIME) + .duration(UPDATED_DURATION) + .venue(UPDATED_VENUE) + .details(UPDATED_DETAILS); + return activity; + } + + @BeforeEach + public void initTest() { + activity = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedActivity != null) { + activityRepository.delete(insertedActivity); + insertedActivity = null; + } + } + + @Test + @Transactional + void createActivity() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + var returnedActivityDTO = om.readValue( + restActivityMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + ActivityDTO.class + ); + + // Validate the Activity in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedActivity = activityMapper.toEntity(returnedActivityDTO); + assertActivityUpdatableFieldsEquals(returnedActivity, getPersistedActivity(returnedActivity)); + + insertedActivity = returnedActivity; + } + + @Test + @Transactional + void createActivityWithExistingId() throws Exception { + // Create the Activity with an existing ID + activity.setId(1L); + ActivityDTO activityDTO = activityMapper.toDto(activity); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restActivityMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void checkActivityTimeIsRequired() throws Exception { + long databaseSizeBeforeTest = getRepositoryCount(); + // set the field null + activity.setActivityTime(null); + + // Create the Activity, which fails. + ActivityDTO activityDTO = activityMapper.toDto(activity); + + restActivityMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityDTO))) + .andExpect(status().isBadRequest()); + + assertSameRepositoryCount(databaseSizeBeforeTest); + } + + @Test + @Transactional + void getAllActivities() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + // Get all the activityList + restActivityMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(activity.getId().intValue()))) + .andExpect(jsonPath("$.[*].activityTime").value(hasItem(DEFAULT_ACTIVITY_TIME.toString()))) + .andExpect(jsonPath("$.[*].duration").value(hasItem(DEFAULT_DURATION))) + .andExpect(jsonPath("$.[*].venue").value(hasItem(DEFAULT_VENUE))) + .andExpect(jsonPath("$.[*].details").value(hasItem(DEFAULT_DETAILS.toString()))); + } + + @Test + @Transactional + void getActivity() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + // Get the activity + restActivityMockMvc + .perform(get(ENTITY_API_URL_ID, activity.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(activity.getId().intValue())) + .andExpect(jsonPath("$.activityTime").value(DEFAULT_ACTIVITY_TIME.toString())) + .andExpect(jsonPath("$.duration").value(DEFAULT_DURATION)) + .andExpect(jsonPath("$.venue").value(DEFAULT_VENUE)) + .andExpect(jsonPath("$.details").value(DEFAULT_DETAILS.toString())); + } + + @Test + @Transactional + void getNonExistingActivity() throws Exception { + // Get the activity + restActivityMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingActivity() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activity + Activity updatedActivity = activityRepository.findById(activity.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedActivity are not directly saved in db + em.detach(updatedActivity); + updatedActivity.activityTime(UPDATED_ACTIVITY_TIME).duration(UPDATED_DURATION).venue(UPDATED_VENUE).details(UPDATED_DETAILS); + ActivityDTO activityDTO = activityMapper.toDto(updatedActivity); + + restActivityMockMvc + .perform( + put(ENTITY_API_URL_ID, activityDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityDTO)) + ) + .andExpect(status().isOk()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedActivityToMatchAllProperties(updatedActivity); + } + + @Test + @Transactional + void putNonExistingActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform( + put(ENTITY_API_URL_ID, activityDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(activityDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateActivityWithPatch() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activity using partial update + Activity partialUpdatedActivity = new Activity(); + partialUpdatedActivity.setId(activity.getId()); + + partialUpdatedActivity.details(UPDATED_DETAILS); + + restActivityMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedActivity.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedActivity)) + ) + .andExpect(status().isOk()); + + // Validate the Activity in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertActivityUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedActivity, activity), getPersistedActivity(activity)); + } + + @Test + @Transactional + void fullUpdateActivityWithPatch() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the activity using partial update + Activity partialUpdatedActivity = new Activity(); + partialUpdatedActivity.setId(activity.getId()); + + partialUpdatedActivity.activityTime(UPDATED_ACTIVITY_TIME).duration(UPDATED_DURATION).venue(UPDATED_VENUE).details(UPDATED_DETAILS); + + restActivityMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedActivity.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedActivity)) + ) + .andExpect(status().isOk()); + + // Validate the Activity in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertActivityUpdatableFieldsEquals(partialUpdatedActivity, getPersistedActivity(partialUpdatedActivity)); + } + + @Test + @Transactional + void patchNonExistingActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform( + patch(ENTITY_API_URL_ID, activityDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(activityDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(activityDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamActivity() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + activity.setId(longCount.incrementAndGet()); + + // Create the Activity + ActivityDTO activityDTO = activityMapper.toDto(activity); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restActivityMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(activityDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Activity in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteActivity() throws Exception { + // Initialize the database + insertedActivity = activityRepository.saveAndFlush(activity); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the activity + restActivityMockMvc + .perform(delete(ENTITY_API_URL_ID, activity.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return activityRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected Activity getPersistedActivity(Activity activity) { + return activityRepository.findById(activity.getId()).orElseThrow(); + } + + protected void assertPersistedActivityToMatchAllProperties(Activity expectedActivity) { + assertActivityAllPropertiesEquals(expectedActivity, getPersistedActivity(expectedActivity)); + } + + protected void assertPersistedActivityToMatchUpdatableProperties(Activity expectedActivity) { + assertActivityAllUpdatablePropertiesEquals(expectedActivity, getPersistedActivity(expectedActivity)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/CodeTablesResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/CodeTablesResourceIT.java new file mode 100644 index 0000000..21325cf --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/CodeTablesResourceIT.java @@ -0,0 +1,444 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.CodeTablesAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.CodeTables; +import com.teamsixnus.scaleup.repository.CodeTablesRepository; +import com.teamsixnus.scaleup.service.dto.CodeTablesDTO; +import com.teamsixnus.scaleup.service.mapper.CodeTablesMapper; +import jakarta.persistence.EntityManager; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link CodeTablesResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class CodeTablesResourceIT { + + private static final String DEFAULT_CATEGORY = "AAAAAAAAAA"; + private static final String UPDATED_CATEGORY = "BBBBBBBBBB"; + + private static final String DEFAULT_CODE_KEY = "AAAAAAAAAA"; + private static final String UPDATED_CODE_KEY = "BBBBBBBBBB"; + + private static final String DEFAULT_CODE_VALUE = "AAAAAAAAAA"; + private static final String UPDATED_CODE_VALUE = "BBBBBBBBBB"; + + private static final String ENTITY_API_URL = "/api/code-tables"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private CodeTablesRepository codeTablesRepository; + + @Autowired + private CodeTablesMapper codeTablesMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restCodeTablesMockMvc; + + private CodeTables codeTables; + + private CodeTables insertedCodeTables; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static CodeTables createEntity(EntityManager em) { + CodeTables codeTables = new CodeTables().category(DEFAULT_CATEGORY).codeKey(DEFAULT_CODE_KEY).codeValue(DEFAULT_CODE_VALUE); + return codeTables; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static CodeTables createUpdatedEntity(EntityManager em) { + CodeTables codeTables = new CodeTables().category(UPDATED_CATEGORY).codeKey(UPDATED_CODE_KEY).codeValue(UPDATED_CODE_VALUE); + return codeTables; + } + + @BeforeEach + public void initTest() { + codeTables = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedCodeTables != null) { + codeTablesRepository.delete(insertedCodeTables); + insertedCodeTables = null; + } + } + + @Test + @Transactional + void createCodeTables() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + var returnedCodeTablesDTO = om.readValue( + restCodeTablesMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(codeTablesDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + CodeTablesDTO.class + ); + + // Validate the CodeTables in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedCodeTables = codeTablesMapper.toEntity(returnedCodeTablesDTO); + assertCodeTablesUpdatableFieldsEquals(returnedCodeTables, getPersistedCodeTables(returnedCodeTables)); + + insertedCodeTables = returnedCodeTables; + } + + @Test + @Transactional + void createCodeTablesWithExistingId() throws Exception { + // Create the CodeTables with an existing ID + codeTables.setId(1L); + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restCodeTablesMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(codeTablesDTO))) + .andExpect(status().isBadRequest()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void getAllCodeTables() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + // Get all the codeTablesList + restCodeTablesMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(codeTables.getId().intValue()))) + .andExpect(jsonPath("$.[*].category").value(hasItem(DEFAULT_CATEGORY))) + .andExpect(jsonPath("$.[*].codeKey").value(hasItem(DEFAULT_CODE_KEY))) + .andExpect(jsonPath("$.[*].codeValue").value(hasItem(DEFAULT_CODE_VALUE))); + } + + @Test + @Transactional + void getCodeTables() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + // Get the codeTables + restCodeTablesMockMvc + .perform(get(ENTITY_API_URL_ID, codeTables.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(codeTables.getId().intValue())) + .andExpect(jsonPath("$.category").value(DEFAULT_CATEGORY)) + .andExpect(jsonPath("$.codeKey").value(DEFAULT_CODE_KEY)) + .andExpect(jsonPath("$.codeValue").value(DEFAULT_CODE_VALUE)); + } + + @Test + @Transactional + void getNonExistingCodeTables() throws Exception { + // Get the codeTables + restCodeTablesMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingCodeTables() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the codeTables + CodeTables updatedCodeTables = codeTablesRepository.findById(codeTables.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedCodeTables are not directly saved in db + em.detach(updatedCodeTables); + updatedCodeTables.category(UPDATED_CATEGORY).codeKey(UPDATED_CODE_KEY).codeValue(UPDATED_CODE_VALUE); + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(updatedCodeTables); + + restCodeTablesMockMvc + .perform( + put(ENTITY_API_URL_ID, codeTablesDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(codeTablesDTO)) + ) + .andExpect(status().isOk()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedCodeTablesToMatchAllProperties(updatedCodeTables); + } + + @Test + @Transactional + void putNonExistingCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform( + put(ENTITY_API_URL_ID, codeTablesDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(codeTablesDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(codeTablesDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(codeTablesDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateCodeTablesWithPatch() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the codeTables using partial update + CodeTables partialUpdatedCodeTables = new CodeTables(); + partialUpdatedCodeTables.setId(codeTables.getId()); + + partialUpdatedCodeTables.codeKey(UPDATED_CODE_KEY).codeValue(UPDATED_CODE_VALUE); + + restCodeTablesMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedCodeTables.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedCodeTables)) + ) + .andExpect(status().isOk()); + + // Validate the CodeTables in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertCodeTablesUpdatableFieldsEquals( + createUpdateProxyForBean(partialUpdatedCodeTables, codeTables), + getPersistedCodeTables(codeTables) + ); + } + + @Test + @Transactional + void fullUpdateCodeTablesWithPatch() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the codeTables using partial update + CodeTables partialUpdatedCodeTables = new CodeTables(); + partialUpdatedCodeTables.setId(codeTables.getId()); + + partialUpdatedCodeTables.category(UPDATED_CATEGORY).codeKey(UPDATED_CODE_KEY).codeValue(UPDATED_CODE_VALUE); + + restCodeTablesMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedCodeTables.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedCodeTables)) + ) + .andExpect(status().isOk()); + + // Validate the CodeTables in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertCodeTablesUpdatableFieldsEquals(partialUpdatedCodeTables, getPersistedCodeTables(partialUpdatedCodeTables)); + } + + @Test + @Transactional + void patchNonExistingCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform( + patch(ENTITY_API_URL_ID, codeTablesDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(codeTablesDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(codeTablesDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamCodeTables() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + codeTables.setId(longCount.incrementAndGet()); + + // Create the CodeTables + CodeTablesDTO codeTablesDTO = codeTablesMapper.toDto(codeTables); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restCodeTablesMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(codeTablesDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the CodeTables in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteCodeTables() throws Exception { + // Initialize the database + insertedCodeTables = codeTablesRepository.saveAndFlush(codeTables); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the codeTables + restCodeTablesMockMvc + .perform(delete(ENTITY_API_URL_ID, codeTables.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return codeTablesRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected CodeTables getPersistedCodeTables(CodeTables codeTables) { + return codeTablesRepository.findById(codeTables.getId()).orElseThrow(); + } + + protected void assertPersistedCodeTablesToMatchAllProperties(CodeTables expectedCodeTables) { + assertCodeTablesAllPropertiesEquals(expectedCodeTables, getPersistedCodeTables(expectedCodeTables)); + } + + protected void assertPersistedCodeTablesToMatchUpdatableProperties(CodeTables expectedCodeTables) { + assertCodeTablesAllUpdatablePropertiesEquals(expectedCodeTables, getPersistedCodeTables(expectedCodeTables)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/MessageResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/MessageResourceIT.java new file mode 100644 index 0000000..2bcc44d --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/MessageResourceIT.java @@ -0,0 +1,456 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.MessageAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.Message; +import com.teamsixnus.scaleup.repository.MessageRepository; +import com.teamsixnus.scaleup.service.dto.MessageDTO; +import com.teamsixnus.scaleup.service.mapper.MessageMapper; +import jakarta.persistence.EntityManager; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link MessageResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class MessageResourceIT { + + private static final String DEFAULT_CONTENT = "AAAAAAAAAA"; + private static final String UPDATED_CONTENT = "BBBBBBBBBB"; + + private static final Instant DEFAULT_SENT_AT = Instant.ofEpochMilli(0L); + private static final Instant UPDATED_SENT_AT = Instant.now().truncatedTo(ChronoUnit.MILLIS); + + private static final Boolean DEFAULT_IS_DELETED = false; + private static final Boolean UPDATED_IS_DELETED = true; + + private static final String ENTITY_API_URL = "/api/messages"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private MessageRepository messageRepository; + + @Autowired + private MessageMapper messageMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restMessageMockMvc; + + private Message message; + + private Message insertedMessage; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Message createEntity(EntityManager em) { + Message message = new Message().content(DEFAULT_CONTENT).sentAt(DEFAULT_SENT_AT).isDeleted(DEFAULT_IS_DELETED); + return message; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Message createUpdatedEntity(EntityManager em) { + Message message = new Message().content(UPDATED_CONTENT).sentAt(UPDATED_SENT_AT).isDeleted(UPDATED_IS_DELETED); + return message; + } + + @BeforeEach + public void initTest() { + message = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedMessage != null) { + messageRepository.delete(insertedMessage); + insertedMessage = null; + } + } + + @Test + @Transactional + void createMessage() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + var returnedMessageDTO = om.readValue( + restMessageMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + MessageDTO.class + ); + + // Validate the Message in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedMessage = messageMapper.toEntity(returnedMessageDTO); + assertMessageUpdatableFieldsEquals(returnedMessage, getPersistedMessage(returnedMessage)); + + insertedMessage = returnedMessage; + } + + @Test + @Transactional + void createMessageWithExistingId() throws Exception { + // Create the Message with an existing ID + message.setId(1L); + MessageDTO messageDTO = messageMapper.toDto(message); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restMessageMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void checkSentAtIsRequired() throws Exception { + long databaseSizeBeforeTest = getRepositoryCount(); + // set the field null + message.setSentAt(null); + + // Create the Message, which fails. + MessageDTO messageDTO = messageMapper.toDto(message); + + restMessageMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO))) + .andExpect(status().isBadRequest()); + + assertSameRepositoryCount(databaseSizeBeforeTest); + } + + @Test + @Transactional + void getAllMessages() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + // Get all the messageList + restMessageMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(message.getId().intValue()))) + .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString()))) + .andExpect(jsonPath("$.[*].sentAt").value(hasItem(DEFAULT_SENT_AT.toString()))) + .andExpect(jsonPath("$.[*].isDeleted").value(hasItem(DEFAULT_IS_DELETED.booleanValue()))); + } + + @Test + @Transactional + void getMessage() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + // Get the message + restMessageMockMvc + .perform(get(ENTITY_API_URL_ID, message.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(message.getId().intValue())) + .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString())) + .andExpect(jsonPath("$.sentAt").value(DEFAULT_SENT_AT.toString())) + .andExpect(jsonPath("$.isDeleted").value(DEFAULT_IS_DELETED.booleanValue())); + } + + @Test + @Transactional + void getNonExistingMessage() throws Exception { + // Get the message + restMessageMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingMessage() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the message + Message updatedMessage = messageRepository.findById(message.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedMessage are not directly saved in db + em.detach(updatedMessage); + updatedMessage.content(UPDATED_CONTENT).sentAt(UPDATED_SENT_AT).isDeleted(UPDATED_IS_DELETED); + MessageDTO messageDTO = messageMapper.toDto(updatedMessage); + + restMessageMockMvc + .perform( + put(ENTITY_API_URL_ID, messageDTO.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO)) + ) + .andExpect(status().isOk()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedMessageToMatchAllProperties(updatedMessage); + } + + @Test + @Transactional + void putNonExistingMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform( + put(ENTITY_API_URL_ID, messageDTO.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(messageDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(messageDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateMessageWithPatch() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the message using partial update + Message partialUpdatedMessage = new Message(); + partialUpdatedMessage.setId(message.getId()); + + partialUpdatedMessage.content(UPDATED_CONTENT); + + restMessageMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedMessage.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedMessage)) + ) + .andExpect(status().isOk()); + + // Validate the Message in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertMessageUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedMessage, message), getPersistedMessage(message)); + } + + @Test + @Transactional + void fullUpdateMessageWithPatch() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the message using partial update + Message partialUpdatedMessage = new Message(); + partialUpdatedMessage.setId(message.getId()); + + partialUpdatedMessage.content(UPDATED_CONTENT).sentAt(UPDATED_SENT_AT).isDeleted(UPDATED_IS_DELETED); + + restMessageMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedMessage.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedMessage)) + ) + .andExpect(status().isOk()); + + // Validate the Message in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertMessageUpdatableFieldsEquals(partialUpdatedMessage, getPersistedMessage(partialUpdatedMessage)); + } + + @Test + @Transactional + void patchNonExistingMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform( + patch(ENTITY_API_URL_ID, messageDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(messageDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(messageDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamMessage() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + message.setId(longCount.incrementAndGet()); + + // Create the Message + MessageDTO messageDTO = messageMapper.toDto(message); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restMessageMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(messageDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Message in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteMessage() throws Exception { + // Initialize the database + insertedMessage = messageRepository.saveAndFlush(message); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the message + restMessageMockMvc + .perform(delete(ENTITY_API_URL_ID, message.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return messageRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected Message getPersistedMessage(Message message) { + return messageRepository.findById(message.getId()).orElseThrow(); + } + + protected void assertPersistedMessageToMatchAllProperties(Message expectedMessage) { + assertMessageAllPropertiesEquals(expectedMessage, getPersistedMessage(expectedMessage)); + } + + protected void assertPersistedMessageToMatchUpdatableProperties(Message expectedMessage) { + assertMessageAllUpdatablePropertiesEquals(expectedMessage, getPersistedMessage(expectedMessage)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/NotificationResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/NotificationResourceIT.java new file mode 100644 index 0000000..2111612 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/NotificationResourceIT.java @@ -0,0 +1,451 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.NotificationAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.Notification; +import com.teamsixnus.scaleup.repository.NotificationRepository; +import com.teamsixnus.scaleup.service.dto.NotificationDTO; +import com.teamsixnus.scaleup.service.mapper.NotificationMapper; +import jakarta.persistence.EntityManager; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link NotificationResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class NotificationResourceIT { + + private static final UUID DEFAULT_NOTIFICATION_REF_ID = UUID.randomUUID(); + private static final UUID UPDATED_NOTIFICATION_REF_ID = UUID.randomUUID(); + + private static final String DEFAULT_CONTENT = "AAAAAAAAAA"; + private static final String UPDATED_CONTENT = "BBBBBBBBBB"; + + private static final Boolean DEFAULT_IS_READ = false; + private static final Boolean UPDATED_IS_READ = true; + + private static final String ENTITY_API_URL = "/api/notifications"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private NotificationRepository notificationRepository; + + @Autowired + private NotificationMapper notificationMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restNotificationMockMvc; + + private Notification notification; + + private Notification insertedNotification; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Notification createEntity(EntityManager em) { + Notification notification = new Notification() + .notificationRefId(DEFAULT_NOTIFICATION_REF_ID) + .content(DEFAULT_CONTENT) + .isRead(DEFAULT_IS_READ); + return notification; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Notification createUpdatedEntity(EntityManager em) { + Notification notification = new Notification() + .notificationRefId(UPDATED_NOTIFICATION_REF_ID) + .content(UPDATED_CONTENT) + .isRead(UPDATED_IS_READ); + return notification; + } + + @BeforeEach + public void initTest() { + notification = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedNotification != null) { + notificationRepository.delete(insertedNotification); + insertedNotification = null; + } + } + + @Test + @Transactional + void createNotification() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + var returnedNotificationDTO = om.readValue( + restNotificationMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(notificationDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + NotificationDTO.class + ); + + // Validate the Notification in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedNotification = notificationMapper.toEntity(returnedNotificationDTO); + assertNotificationUpdatableFieldsEquals(returnedNotification, getPersistedNotification(returnedNotification)); + + insertedNotification = returnedNotification; + } + + @Test + @Transactional + void createNotificationWithExistingId() throws Exception { + // Create the Notification with an existing ID + notification.setId(1L); + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restNotificationMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(notificationDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void getAllNotifications() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + // Get all the notificationList + restNotificationMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(notification.getId().intValue()))) + .andExpect(jsonPath("$.[*].notificationRefId").value(hasItem(DEFAULT_NOTIFICATION_REF_ID.toString()))) + .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString()))) + .andExpect(jsonPath("$.[*].isRead").value(hasItem(DEFAULT_IS_READ.booleanValue()))); + } + + @Test + @Transactional + void getNotification() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + // Get the notification + restNotificationMockMvc + .perform(get(ENTITY_API_URL_ID, notification.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(notification.getId().intValue())) + .andExpect(jsonPath("$.notificationRefId").value(DEFAULT_NOTIFICATION_REF_ID.toString())) + .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString())) + .andExpect(jsonPath("$.isRead").value(DEFAULT_IS_READ.booleanValue())); + } + + @Test + @Transactional + void getNonExistingNotification() throws Exception { + // Get the notification + restNotificationMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingNotification() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the notification + Notification updatedNotification = notificationRepository.findById(notification.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedNotification are not directly saved in db + em.detach(updatedNotification); + updatedNotification.notificationRefId(UPDATED_NOTIFICATION_REF_ID).content(UPDATED_CONTENT).isRead(UPDATED_IS_READ); + NotificationDTO notificationDTO = notificationMapper.toDto(updatedNotification); + + restNotificationMockMvc + .perform( + put(ENTITY_API_URL_ID, notificationDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(notificationDTO)) + ) + .andExpect(status().isOk()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedNotificationToMatchAllProperties(updatedNotification); + } + + @Test + @Transactional + void putNonExistingNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform( + put(ENTITY_API_URL_ID, notificationDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(notificationDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(notificationDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(notificationDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateNotificationWithPatch() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the notification using partial update + Notification partialUpdatedNotification = new Notification(); + partialUpdatedNotification.setId(notification.getId()); + + partialUpdatedNotification.notificationRefId(UPDATED_NOTIFICATION_REF_ID).content(UPDATED_CONTENT); + + restNotificationMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedNotification.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedNotification)) + ) + .andExpect(status().isOk()); + + // Validate the Notification in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertNotificationUpdatableFieldsEquals( + createUpdateProxyForBean(partialUpdatedNotification, notification), + getPersistedNotification(notification) + ); + } + + @Test + @Transactional + void fullUpdateNotificationWithPatch() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the notification using partial update + Notification partialUpdatedNotification = new Notification(); + partialUpdatedNotification.setId(notification.getId()); + + partialUpdatedNotification.notificationRefId(UPDATED_NOTIFICATION_REF_ID).content(UPDATED_CONTENT).isRead(UPDATED_IS_READ); + + restNotificationMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedNotification.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedNotification)) + ) + .andExpect(status().isOk()); + + // Validate the Notification in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertNotificationUpdatableFieldsEquals(partialUpdatedNotification, getPersistedNotification(partialUpdatedNotification)); + } + + @Test + @Transactional + void patchNonExistingNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform( + patch(ENTITY_API_URL_ID, notificationDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(notificationDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(notificationDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamNotification() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + notification.setId(longCount.incrementAndGet()); + + // Create the Notification + NotificationDTO notificationDTO = notificationMapper.toDto(notification); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restNotificationMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(notificationDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Notification in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteNotification() throws Exception { + // Initialize the database + insertedNotification = notificationRepository.saveAndFlush(notification); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the notification + restNotificationMockMvc + .perform(delete(ENTITY_API_URL_ID, notification.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return notificationRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected Notification getPersistedNotification(Notification notification) { + return notificationRepository.findById(notification.getId()).orElseThrow(); + } + + protected void assertPersistedNotificationToMatchAllProperties(Notification expectedNotification) { + assertNotificationAllPropertiesEquals(expectedNotification, getPersistedNotification(expectedNotification)); + } + + protected void assertPersistedNotificationToMatchUpdatableProperties(Notification expectedNotification) { + assertNotificationAllUpdatablePropertiesEquals(expectedNotification, getPersistedNotification(expectedNotification)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/SkillResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/SkillResourceIT.java new file mode 100644 index 0000000..4c39a56 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/SkillResourceIT.java @@ -0,0 +1,480 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.SkillAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.Skill; +import com.teamsixnus.scaleup.repository.SkillRepository; +import com.teamsixnus.scaleup.service.dto.SkillDTO; +import com.teamsixnus.scaleup.service.mapper.SkillMapper; +import jakarta.persistence.EntityManager; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link SkillResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser +class SkillResourceIT { + + private static final String DEFAULT_SKILL_NAME = "AAAAAAAAAA"; + private static final String UPDATED_SKILL_NAME = "BBBBBBBBBB"; + + private static final String DEFAULT_INDIVIDUAL_SKILL_DESC = "AAAAAAAAAA"; + private static final String UPDATED_INDIVIDUAL_SKILL_DESC = "BBBBBBBBBB"; + + private static final Integer DEFAULT_YEARS_OF_EXP = 1; + private static final Integer UPDATED_YEARS_OF_EXP = 2; + + private static final String ENTITY_API_URL = "/api/skills"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private SkillRepository skillRepository; + + @Autowired + private SkillMapper skillMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restSkillMockMvc; + + private Skill skill; + + private Skill insertedSkill; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Skill createEntity(EntityManager em) { + Skill skill = new Skill() + .skillName(DEFAULT_SKILL_NAME) + .individualSkillDesc(DEFAULT_INDIVIDUAL_SKILL_DESC) + .yearsOfExp(DEFAULT_YEARS_OF_EXP); + return skill; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Skill createUpdatedEntity(EntityManager em) { + Skill skill = new Skill() + .skillName(UPDATED_SKILL_NAME) + .individualSkillDesc(UPDATED_INDIVIDUAL_SKILL_DESC) + .yearsOfExp(UPDATED_YEARS_OF_EXP); + return skill; + } + + @BeforeEach + public void initTest() { + skill = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedSkill != null) { + skillRepository.delete(insertedSkill); + insertedSkill = null; + } + } + + @Test + @Transactional + void createSkill() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + var returnedSkillDTO = om.readValue( + restSkillMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + SkillDTO.class + ); + + // Validate the Skill in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedSkill = skillMapper.toEntity(returnedSkillDTO); + assertSkillUpdatableFieldsEquals(returnedSkill, getPersistedSkill(returnedSkill)); + + insertedSkill = returnedSkill; + } + + @Test + @Transactional + void createSkillWithExistingId() throws Exception { + // Create the Skill with an existing ID + skill.setId(1L); + SkillDTO skillDTO = skillMapper.toDto(skill); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restSkillMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void checkSkillNameIsRequired() throws Exception { + long databaseSizeBeforeTest = getRepositoryCount(); + // set the field null + skill.setSkillName(null); + + // Create the Skill, which fails. + SkillDTO skillDTO = skillMapper.toDto(skill); + + restSkillMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isBadRequest()); + + assertSameRepositoryCount(databaseSizeBeforeTest); + } + + @Test + @Transactional + void checkYearsOfExpIsRequired() throws Exception { + long databaseSizeBeforeTest = getRepositoryCount(); + // set the field null + skill.setYearsOfExp(null); + + // Create the Skill, which fails. + SkillDTO skillDTO = skillMapper.toDto(skill); + + restSkillMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isBadRequest()); + + assertSameRepositoryCount(databaseSizeBeforeTest); + } + + @Test + @Transactional + void getAllSkills() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + // Get all the skillList + restSkillMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(skill.getId().intValue()))) + .andExpect(jsonPath("$.[*].skillName").value(hasItem(DEFAULT_SKILL_NAME))) + .andExpect(jsonPath("$.[*].individualSkillDesc").value(hasItem(DEFAULT_INDIVIDUAL_SKILL_DESC))) + .andExpect(jsonPath("$.[*].yearsOfExp").value(hasItem(DEFAULT_YEARS_OF_EXP))); + } + + @Test + @Transactional + void getSkill() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + // Get the skill + restSkillMockMvc + .perform(get(ENTITY_API_URL_ID, skill.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(skill.getId().intValue())) + .andExpect(jsonPath("$.skillName").value(DEFAULT_SKILL_NAME)) + .andExpect(jsonPath("$.individualSkillDesc").value(DEFAULT_INDIVIDUAL_SKILL_DESC)) + .andExpect(jsonPath("$.yearsOfExp").value(DEFAULT_YEARS_OF_EXP)); + } + + @Test + @Transactional + void getNonExistingSkill() throws Exception { + // Get the skill + restSkillMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingSkill() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the skill + Skill updatedSkill = skillRepository.findById(skill.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedSkill are not directly saved in db + em.detach(updatedSkill); + updatedSkill.skillName(UPDATED_SKILL_NAME).individualSkillDesc(UPDATED_INDIVIDUAL_SKILL_DESC).yearsOfExp(UPDATED_YEARS_OF_EXP); + SkillDTO skillDTO = skillMapper.toDto(updatedSkill); + + restSkillMockMvc + .perform( + put(ENTITY_API_URL_ID, skillDTO.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO)) + ) + .andExpect(status().isOk()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedSkillToMatchAllProperties(updatedSkill); + } + + @Test + @Transactional + void putNonExistingSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform( + put(ENTITY_API_URL_ID, skillDTO.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(skillDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateSkillWithPatch() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the skill using partial update + Skill partialUpdatedSkill = new Skill(); + partialUpdatedSkill.setId(skill.getId()); + + partialUpdatedSkill.skillName(UPDATED_SKILL_NAME).yearsOfExp(UPDATED_YEARS_OF_EXP); + + restSkillMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedSkill.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedSkill)) + ) + .andExpect(status().isOk()); + + // Validate the Skill in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertSkillUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedSkill, skill), getPersistedSkill(skill)); + } + + @Test + @Transactional + void fullUpdateSkillWithPatch() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the skill using partial update + Skill partialUpdatedSkill = new Skill(); + partialUpdatedSkill.setId(skill.getId()); + + partialUpdatedSkill + .skillName(UPDATED_SKILL_NAME) + .individualSkillDesc(UPDATED_INDIVIDUAL_SKILL_DESC) + .yearsOfExp(UPDATED_YEARS_OF_EXP); + + restSkillMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedSkill.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedSkill)) + ) + .andExpect(status().isOk()); + + // Validate the Skill in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertSkillUpdatableFieldsEquals(partialUpdatedSkill, getPersistedSkill(partialUpdatedSkill)); + } + + @Test + @Transactional + void patchNonExistingSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform( + patch(ENTITY_API_URL_ID, skillDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(skillDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(skillDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamSkill() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + skill.setId(longCount.incrementAndGet()); + + // Create the Skill + SkillDTO skillDTO = skillMapper.toDto(skill); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restSkillMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(skillDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the Skill in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteSkill() throws Exception { + // Initialize the database + insertedSkill = skillRepository.saveAndFlush(skill); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the skill + restSkillMockMvc + .perform(delete(ENTITY_API_URL_ID, skill.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return skillRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected Skill getPersistedSkill(Skill skill) { + return skillRepository.findById(skill.getId()).orElseThrow(); + } + + protected void assertPersistedSkillToMatchAllProperties(Skill expectedSkill) { + assertSkillAllPropertiesEquals(expectedSkill, getPersistedSkill(expectedSkill)); + } + + protected void assertPersistedSkillToMatchUpdatableProperties(Skill expectedSkill) { + assertSkillAllUpdatablePropertiesEquals(expectedSkill, getPersistedSkill(expectedSkill)); + } +} diff --git a/src/test/java/com/teamsixnus/scaleup/web/rest/UserProfileResourceIT.java b/src/test/java/com/teamsixnus/scaleup/web/rest/UserProfileResourceIT.java new file mode 100644 index 0000000..cb7b823 --- /dev/null +++ b/src/test/java/com/teamsixnus/scaleup/web/rest/UserProfileResourceIT.java @@ -0,0 +1,512 @@ +package com.teamsixnus.scaleup.web.rest; + +import static com.teamsixnus.scaleup.domain.UserProfileAsserts.*; +import static com.teamsixnus.scaleup.web.rest.TestUtil.createUpdateProxyForBean; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.teamsixnus.scaleup.IntegrationTest; +import com.teamsixnus.scaleup.domain.User; +import com.teamsixnus.scaleup.domain.UserProfile; +import com.teamsixnus.scaleup.repository.UserProfileRepository; +import com.teamsixnus.scaleup.repository.UserRepository; +import com.teamsixnus.scaleup.service.UserProfileService; +import com.teamsixnus.scaleup.service.dto.UserProfileDTO; +import com.teamsixnus.scaleup.service.mapper.UserProfileMapper; +import jakarta.persistence.EntityManager; +import java.util.ArrayList; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link UserProfileResource} REST controller. + */ +@IntegrationTest +@ExtendWith(MockitoExtension.class) +@AutoConfigureMockMvc +@WithMockUser +class UserProfileResourceIT { + + private static final String DEFAULT_NICKNAME = "AAAAAAAAAA"; + private static final String UPDATED_NICKNAME = "BBBBBBBBBB"; + + private static final String DEFAULT_JOB_ROLE = "AAAAAAAAAA"; + private static final String UPDATED_JOB_ROLE = "BBBBBBBBBB"; + + private static final String DEFAULT_ABOUT_ME = "AAAAAAAAAA"; + private static final String UPDATED_ABOUT_ME = "BBBBBBBBBB"; + + private static final String DEFAULT_PROFILE_PICTURE = "AAAAAAAAAA"; + private static final String UPDATED_PROFILE_PICTURE = "BBBBBBBBBB"; + + private static final String ENTITY_API_URL = "/api/user-profiles"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; + + private static Random random = new Random(); + private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); + + @Autowired + private ObjectMapper om; + + @Autowired + private UserProfileRepository userProfileRepository; + + @Autowired + private UserRepository userRepository; + + @Mock + private UserProfileRepository userProfileRepositoryMock; + + @Autowired + private UserProfileMapper userProfileMapper; + + @Mock + private UserProfileService userProfileServiceMock; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restUserProfileMockMvc; + + private UserProfile userProfile; + + private UserProfile insertedUserProfile; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static UserProfile createEntity(EntityManager em) { + UserProfile userProfile = new UserProfile() + .nickname(DEFAULT_NICKNAME) + .jobRole(DEFAULT_JOB_ROLE) + .aboutMe(DEFAULT_ABOUT_ME) + .profilePicture(DEFAULT_PROFILE_PICTURE); + // Add required entity + User user = UserResourceIT.createEntity(em); + em.persist(user); + em.flush(); + userProfile.setUser(user); + return userProfile; + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static UserProfile createUpdatedEntity(EntityManager em) { + UserProfile userProfile = new UserProfile() + .nickname(UPDATED_NICKNAME) + .jobRole(UPDATED_JOB_ROLE) + .aboutMe(UPDATED_ABOUT_ME) + .profilePicture(UPDATED_PROFILE_PICTURE); + // Add required entity + User user = UserResourceIT.createEntity(em); + em.persist(user); + em.flush(); + userProfile.setUser(user); + return userProfile; + } + + @BeforeEach + public void initTest() { + userProfile = createEntity(em); + } + + @AfterEach + public void cleanup() { + if (insertedUserProfile != null) { + userProfileRepository.delete(insertedUserProfile); + insertedUserProfile = null; + } + } + + @Test + @Transactional + void createUserProfile() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + var returnedUserProfileDTO = om.readValue( + restUserProfileMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userProfileDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + UserProfileDTO.class + ); + + // Validate the UserProfile in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + var returnedUserProfile = userProfileMapper.toEntity(returnedUserProfileDTO); + assertUserProfileUpdatableFieldsEquals(returnedUserProfile, getPersistedUserProfile(returnedUserProfile)); + + insertedUserProfile = returnedUserProfile; + } + + @Test + @Transactional + void createUserProfileWithExistingId() throws Exception { + // Create the UserProfile with an existing ID + userProfile.setId(1L); + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserProfileMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userProfileDTO))) + .andExpect(status().isBadRequest()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void getAllUserProfiles() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + // Get all the userProfileList + restUserProfileMockMvc + .perform(get(ENTITY_API_URL + "?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(userProfile.getId().intValue()))) + .andExpect(jsonPath("$.[*].nickname").value(hasItem(DEFAULT_NICKNAME))) + .andExpect(jsonPath("$.[*].jobRole").value(hasItem(DEFAULT_JOB_ROLE))) + .andExpect(jsonPath("$.[*].aboutMe").value(hasItem(DEFAULT_ABOUT_ME))) + .andExpect(jsonPath("$.[*].profilePicture").value(hasItem(DEFAULT_PROFILE_PICTURE))); + } + + @SuppressWarnings({ "unchecked" }) + void getAllUserProfilesWithEagerRelationshipsIsEnabled() throws Exception { + when(userProfileServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + + restUserProfileMockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")).andExpect(status().isOk()); + + verify(userProfileServiceMock, times(1)).findAllWithEagerRelationships(any()); + } + + @SuppressWarnings({ "unchecked" }) + void getAllUserProfilesWithEagerRelationshipsIsNotEnabled() throws Exception { + when(userProfileServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + + restUserProfileMockMvc.perform(get(ENTITY_API_URL + "?eagerload=false")).andExpect(status().isOk()); + verify(userProfileRepositoryMock, times(1)).findAll(any(Pageable.class)); + } + + @Test + @Transactional + void getUserProfile() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + // Get the userProfile + restUserProfileMockMvc + .perform(get(ENTITY_API_URL_ID, userProfile.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.id").value(userProfile.getId().intValue())) + .andExpect(jsonPath("$.nickname").value(DEFAULT_NICKNAME)) + .andExpect(jsonPath("$.jobRole").value(DEFAULT_JOB_ROLE)) + .andExpect(jsonPath("$.aboutMe").value(DEFAULT_ABOUT_ME)) + .andExpect(jsonPath("$.profilePicture").value(DEFAULT_PROFILE_PICTURE)); + } + + @Test + @Transactional + void getNonExistingUserProfile() throws Exception { + // Get the userProfile + restUserProfileMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void putExistingUserProfile() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the userProfile + UserProfile updatedUserProfile = userProfileRepository.findById(userProfile.getId()).orElseThrow(); + // Disconnect from session so that the updates on updatedUserProfile are not directly saved in db + em.detach(updatedUserProfile); + updatedUserProfile + .nickname(UPDATED_NICKNAME) + .jobRole(UPDATED_JOB_ROLE) + .aboutMe(UPDATED_ABOUT_ME) + .profilePicture(UPDATED_PROFILE_PICTURE); + UserProfileDTO userProfileDTO = userProfileMapper.toDto(updatedUserProfile); + + restUserProfileMockMvc + .perform( + put(ENTITY_API_URL_ID, userProfileDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(userProfileDTO)) + ) + .andExpect(status().isOk()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertPersistedUserProfileToMatchAllProperties(updatedUserProfile); + } + + @Test + @Transactional + void putNonExistingUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform( + put(ENTITY_API_URL_ID, userProfileDTO.getId()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(userProfileDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithIdMismatchUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform( + put(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(userProfileDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void putWithMissingIdPathParamUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userProfileDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void partialUpdateUserProfileWithPatch() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the userProfile using partial update + UserProfile partialUpdatedUserProfile = new UserProfile(); + partialUpdatedUserProfile.setId(userProfile.getId()); + + partialUpdatedUserProfile.nickname(UPDATED_NICKNAME).jobRole(UPDATED_JOB_ROLE).profilePicture(UPDATED_PROFILE_PICTURE); + + restUserProfileMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedUserProfile.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedUserProfile)) + ) + .andExpect(status().isOk()); + + // Validate the UserProfile in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertUserProfileUpdatableFieldsEquals( + createUpdateProxyForBean(partialUpdatedUserProfile, userProfile), + getPersistedUserProfile(userProfile) + ); + } + + @Test + @Transactional + void fullUpdateUserProfileWithPatch() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + long databaseSizeBeforeUpdate = getRepositoryCount(); + + // Update the userProfile using partial update + UserProfile partialUpdatedUserProfile = new UserProfile(); + partialUpdatedUserProfile.setId(userProfile.getId()); + + partialUpdatedUserProfile + .nickname(UPDATED_NICKNAME) + .jobRole(UPDATED_JOB_ROLE) + .aboutMe(UPDATED_ABOUT_ME) + .profilePicture(UPDATED_PROFILE_PICTURE); + + restUserProfileMockMvc + .perform( + patch(ENTITY_API_URL_ID, partialUpdatedUserProfile.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(partialUpdatedUserProfile)) + ) + .andExpect(status().isOk()); + + // Validate the UserProfile in the database + + assertSameRepositoryCount(databaseSizeBeforeUpdate); + assertUserProfileUpdatableFieldsEquals(partialUpdatedUserProfile, getPersistedUserProfile(partialUpdatedUserProfile)); + } + + @Test + @Transactional + void patchNonExistingUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform( + patch(ENTITY_API_URL_ID, userProfileDTO.getId()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(userProfileDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithIdMismatchUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform( + patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) + .contentType("application/merge-patch+json") + .content(om.writeValueAsBytes(userProfileDTO)) + ) + .andExpect(status().isBadRequest()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void patchWithMissingIdPathParamUserProfile() throws Exception { + long databaseSizeBeforeUpdate = getRepositoryCount(); + userProfile.setId(longCount.incrementAndGet()); + + // Create the UserProfile + UserProfileDTO userProfileDTO = userProfileMapper.toDto(userProfile); + + // If url ID doesn't match entity ID, it will throw BadRequestAlertException + restUserProfileMockMvc + .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(userProfileDTO))) + .andExpect(status().isMethodNotAllowed()); + + // Validate the UserProfile in the database + assertSameRepositoryCount(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + void deleteUserProfile() throws Exception { + // Initialize the database + insertedUserProfile = userProfileRepository.saveAndFlush(userProfile); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the userProfile + restUserProfileMockMvc + .perform(delete(ENTITY_API_URL_ID, userProfile.getId()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return userProfileRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected UserProfile getPersistedUserProfile(UserProfile userProfile) { + return userProfileRepository.findById(userProfile.getId()).orElseThrow(); + } + + protected void assertPersistedUserProfileToMatchAllProperties(UserProfile expectedUserProfile) { + assertUserProfileAllPropertiesEquals(expectedUserProfile, getPersistedUserProfile(expectedUserProfile)); + } + + protected void assertPersistedUserProfileToMatchUpdatableProperties(UserProfile expectedUserProfile) { + assertUserProfileAllUpdatablePropertiesEquals(expectedUserProfile, getPersistedUserProfile(expectedUserProfile)); + } +} From f269a5c724e980f76a261316d924a0dcab2bfffc Mon Sep 17 00:00:00 2001 From: "shenan.quek" <77522687+SQUEK011@users.noreply.github.com> Date: Sun, 25 Aug 2024 22:53:59 +0800 Subject: [PATCH 2/3] fix pipeline sonarcloud --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index a23eb31..f6443e1 100644 --- a/pom.xml +++ b/pom.xml @@ -76,6 +76,8 @@ 4.0.0.4121 2.43.0 2.5.0 +sayoungestguy +https://sonarcloud.io From 1ae8b7bd7acce3983dfe448e2f4bc0aeade08555 Mon Sep 17 00:00:00 2001 From: "shenan.quek" <77522687+SQUEK011@users.noreply.github.com> Date: Thu, 29 Aug 2024 00:44:32 +0800 Subject: [PATCH 3/3] Finalised Entity Creation + fixed Email Service --- jhipster/Activity.json | 26 ++++++ jhipster/ActivityInvitie.json | 27 ++++++ jhipster/CodeTables.json | 12 +++ jhipster/Message.json | 25 ++++++ jhipster/Notification.json | 25 ++++++ jhipster/Skill.json | 24 ++++++ jhipster/UserProfile.json | 23 +++++ sonar-project.properties | 86 +++++++++---------- .../scaleup/service/MailService.java | 4 +- src/main/resources/.h2.server.properties | 2 +- src/main/resources/config/application-dev.yml | 20 ++++- src/main/resources/config/application.yml | 2 +- .../app/entities/activity/activity-update.tsx | 48 +++++------ .../scaleup/service/MailServiceIT.java | 24 ++++-- 14 files changed, 266 insertions(+), 82 deletions(-) create mode 100644 jhipster/Activity.json create mode 100644 jhipster/ActivityInvitie.json create mode 100644 jhipster/CodeTables.json create mode 100644 jhipster/Message.json create mode 100644 jhipster/Notification.json create mode 100644 jhipster/Skill.json create mode 100644 jhipster/UserProfile.json diff --git a/jhipster/Activity.json b/jhipster/Activity.json new file mode 100644 index 0000000..63e27ac --- /dev/null +++ b/jhipster/Activity.json @@ -0,0 +1,26 @@ +{ + "name": "Activity", + "fields": [ + { "fieldName": "activityTime", "fieldType": "Instant", "fieldValidateRules": ["required"] }, + { "fieldName": "duration", "fieldType": "Integer" }, + { "fieldName": "venue", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 }, + { "fieldName": "details", "fieldType": "TextBlob" } + ], + "relationships": [ + { + "relationshipName": "creatorProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipName": "skill", + "otherEntityName": "skill", + "relationshipType": "many-to-one", + "otherEntityField": "id" + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/ActivityInvitie.json b/jhipster/ActivityInvitie.json new file mode 100644 index 0000000..f65d685 --- /dev/null +++ b/jhipster/ActivityInvitie.json @@ -0,0 +1,27 @@ +{ + "name": "ActivityInvite", + "fields": [{ "fieldName": "willParticipate", "fieldType": "Boolean" }], + "relationships": [ + { + "relationshipName": "activity", + "otherEntityName": "activity", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipName": "inviteeProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipName": "status", + "otherEntityName": "codeTables", + "relationshipType": "many-to-one", + "otherEntityField": "id" + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/CodeTables.json b/jhipster/CodeTables.json new file mode 100644 index 0000000..890a84e --- /dev/null +++ b/jhipster/CodeTables.json @@ -0,0 +1,12 @@ +{ + "name": "CodeTables", + "fields": [ + { "fieldName": "category", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 50 }, + { "fieldName": "codeKey", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 50 }, + { "fieldName": "codeValue", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 } + ], + "relationships": [], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/Message.json b/jhipster/Message.json new file mode 100644 index 0000000..74d2f1f --- /dev/null +++ b/jhipster/Message.json @@ -0,0 +1,25 @@ +{ + "name": "Message", + "fields": [ + { "fieldName": "content", "fieldType": "TextBlob", "fieldValidateRules": ["required"] }, + { "fieldName": "sentAt", "fieldType": "Instant", "fieldValidateRules": ["required"] }, + { "fieldName": "isDeleted", "fieldType": "Boolean" } + ], + "relationships": [ + { + "relationshipName": "senderProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipName": "receiverProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/Notification.json b/jhipster/Notification.json new file mode 100644 index 0000000..7d202b1 --- /dev/null +++ b/jhipster/Notification.json @@ -0,0 +1,25 @@ +{ + "name": "Notification", + "fields": [ + { "fieldName": "notificationRefId", "fieldType": "UUID" }, + { "fieldName": "content", "fieldType": "TextBlob" }, + { "fieldName": "isRead", "fieldType": "Boolean" } + ], + "relationships": [ + { + "relationshipName": "userProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipName": "type", + "otherEntityName": "codeTables", + "relationshipType": "many-to-one", + "otherEntityField": "id" + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/Skill.json b/jhipster/Skill.json new file mode 100644 index 0000000..7a5f863 --- /dev/null +++ b/jhipster/Skill.json @@ -0,0 +1,24 @@ +{ + "name": "Skill", + "fields": [ + { + "fieldName": "skillName", + "fieldType": "String", + "fieldValidateRules": ["required", "maxlength"], + "fieldValidateRulesMaxlength": 255 + }, + { "fieldName": "individualSkillDesc", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 }, + { "fieldName": "yearsOfExp", "fieldType": "Integer", "fieldValidateRules": ["required"] } + ], + "relationships": [ + { + "relationshipName": "userProfile", + "otherEntityName": "userProfile", + "relationshipType": "many-to-one", + "otherEntityField": "id" + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/jhipster/UserProfile.json b/jhipster/UserProfile.json new file mode 100644 index 0000000..1a0db03 --- /dev/null +++ b/jhipster/UserProfile.json @@ -0,0 +1,23 @@ +{ + "name": "UserProfile", + "fields": [ + { "fieldName": "nickname", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 }, + { "fieldName": "jobRole", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 }, + { "fieldName": "aboutMe", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 }, + { "fieldName": "profilePicture", "fieldType": "String", "fieldValidateRules": ["maxlength"], "fieldValidateRulesMaxlength": 255 } + ], + "relationships": [ + { + "relationshipName": "user", + "otherEntityName": "user", + "relationshipType": "one-to-one", + "otherEntityField": "login", + "ownerSide": true, + "relationshipValidateRules": ["required"], + "builtInEntity": true + } + ], + "dto": "mapstruct", + "service": "serviceClass", + "pagination": "infinite-scroll" +} diff --git a/sonar-project.properties b/sonar-project.properties index 2a1f2fd..6a1188e 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,43 +1,43 @@ -sonar.projectKey = scaleup -sonar.projectName = scaleup generated by jhipster - -# Typescript tests files must be inside sources and tests, otherwise `INFO: Test execution data ignored for 80 unknown files, including:` -# is shown. -sonar.sources = src -sonar.tests = src -sonar.host.url = http://localhost:9001 - -sonar.test.inclusions = src/test/**/*.*, src/main/webapp/app/**/*.spec.ts, src/main/webapp/app/**/*.spec.tsx -sonar.coverage.jacoco.xmlReportPaths = target/site/**/jacoco*.xml -sonar.java.codeCoveragePlugin = jacoco -sonar.junit.reportPaths = target/surefire-reports,target/failsafe-reports -sonar.testExecutionReportPaths = target/test-results/jest/TESTS-results-sonar.xml -sonar.javascript.lcov.reportPaths = target/test-results/lcov.info - -sonar.sourceEncoding = UTF-8 -sonar.exclusions = src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.* - -sonar.issue.ignore.multicriteria = S1192,S125,S3437,S4502,S4684,S5145,UndocumentedApi - -# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a JPA-managed field cannot be transient -sonar.issue.ignore.multicriteria.S3437.resourceKey = src/main/java/**/* -sonar.issue.ignore.multicriteria.S3437.ruleKey = squid:S3437 -# Rule https://rules.sonarsource.com/java/RSPEC-4502 is ignored, as for JWT tokens we are not subject to CSRF attack -sonar.issue.ignore.multicriteria.S4502.resourceKey = src/main/java/**/* -sonar.issue.ignore.multicriteria.S4502.ruleKey = java:S4502 -# Rule https://rules.sonarsource.com/java/RSPEC-4684 -sonar.issue.ignore.multicriteria.S4684.resourceKey = src/main/java/**/* -sonar.issue.ignore.multicriteria.S4684.ruleKey = java:S4684 -# Rule https://rules.sonarsource.com/java/RSPEC-5145 log filter is applied -sonar.issue.ignore.multicriteria.S5145.resourceKey = src/main/java/**/* -sonar.issue.ignore.multicriteria.S5145.ruleKey = javasecurity:S5145 -# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and classes, methods and -# arguments names should be self-explanatory -sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey = src/main/java/**/* -sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey = squid:UndocumentedApi -# Rule https://rules.sonarsource.com/java/RSPEC-1192 -sonar.issue.ignore.multicriteria.S1192.resourceKey = src/main/java/**/CacheConfiguration.java -sonar.issue.ignore.multicriteria.S1192.ruleKey = java:S1192 -# Rule https://rules.sonarsource.com/xml/RSPEC-125 -sonar.issue.ignore.multicriteria.S125.resourceKey = src/main/resources/logback-spring.xml -sonar.issue.ignore.multicriteria.S125.ruleKey = xml:S125 +##sonar.projectKey = scaleup +##sonar.projectName = scaleup generated by jhipster +## +### Typescript tests files must be inside sources and tests, otherwise `INFO: Test execution data ignored for 80 unknown files, including:` +### is shown. +##sonar.sources = src +##sonar.tests = src +##sonar.host.url = http://localhost:9001 +# +#sonar.test.inclusions = src/test/**/*.*, src/main/webapp/app/**/*.spec.ts, src/main/webapp/app/**/*.spec.tsx +#sonar.coverage.jacoco.xmlReportPaths = target/site/**/jacoco*.xml +#sonar.java.codeCoveragePlugin = jacoco +#sonar.junit.reportPaths = target/surefire-reports,target/failsafe-reports +#sonar.testExecutionReportPaths = target/test-results/jest/TESTS-results-sonar.xml +#sonar.javascript.lcov.reportPaths = target/test-results/lcov.info +# +#sonar.sourceEncoding = UTF-8 +#sonar.exclusions = src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.* +# +#sonar.issue.ignore.multicriteria = S1192,S125,S3437,S4502,S4684,S5145,UndocumentedApi +# +## Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored, as a JPA-managed field cannot be transient +#sonar.issue.ignore.multicriteria.S3437.resourceKey = src/main/java/**/* +#sonar.issue.ignore.multicriteria.S3437.ruleKey = squid:S3437 +## Rule https://rules.sonarsource.com/java/RSPEC-4502 is ignored, as for JWT tokens we are not subject to CSRF attack +#sonar.issue.ignore.multicriteria.S4502.resourceKey = src/main/java/**/* +#sonar.issue.ignore.multicriteria.S4502.ruleKey = java:S4502 +## Rule https://rules.sonarsource.com/java/RSPEC-4684 +#sonar.issue.ignore.multicriteria.S4684.resourceKey = src/main/java/**/* +#sonar.issue.ignore.multicriteria.S4684.ruleKey = java:S4684 +## Rule https://rules.sonarsource.com/java/RSPEC-5145 log filter is applied +#sonar.issue.ignore.multicriteria.S5145.resourceKey = src/main/java/**/* +#sonar.issue.ignore.multicriteria.S5145.ruleKey = javasecurity:S5145 +## Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and classes, methods and +## arguments names should be self-explanatory +#sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey = src/main/java/**/* +#sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey = squid:UndocumentedApi +## Rule https://rules.sonarsource.com/java/RSPEC-1192 +#sonar.issue.ignore.multicriteria.S1192.resourceKey = src/main/java/**/CacheConfiguration.java +#sonar.issue.ignore.multicriteria.S1192.ruleKey = java:S1192 +## Rule https://rules.sonarsource.com/xml/RSPEC-125 +#sonar.issue.ignore.multicriteria.S125.resourceKey = src/main/resources/logback-spring.xml +#sonar.issue.ignore.multicriteria.S125.ruleKey = xml:S125 diff --git a/src/main/java/com/teamsixnus/scaleup/service/MailService.java b/src/main/java/com/teamsixnus/scaleup/service/MailService.java index 282254a..3ed9711 100644 --- a/src/main/java/com/teamsixnus/scaleup/service/MailService.java +++ b/src/main/java/com/teamsixnus/scaleup/service/MailService.java @@ -71,7 +71,9 @@ private void sendEmailSync(String to, String subject, String content, boolean is try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); message.setTo(to); - message.setFrom(jHipsterProperties.getMail().getFrom()); + // message.setFrom(jHipsterProperties.getMail().getFrom()); + String SenderMail = "MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net"; + message.setFrom(SenderMail); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); diff --git a/src/main/resources/.h2.server.properties b/src/main/resources/.h2.server.properties index 74f3c4e..20cc246 100644 --- a/src/main/resources/.h2.server.properties +++ b/src/main/resources/.h2.server.properties @@ -1,5 +1,5 @@ #H2 Server Properties -#Sun Aug 25 16:51:26 SGT 2024 +#Thu Aug 29 00:36:11 SGT 2024 0=JHipster H2 (Disk)|org.h2.Driver|jdbc\:h2\:file\:./target/h2db/db/scaleup|scaleup webSSL=false webAllowOthers=true diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index d6d7576..12075f9 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -45,11 +45,23 @@ spring: liquibase: # Remove 'faker' if you do not want the sample data to be loaded automatically contexts: dev, faker + # mail: + # host: localhost + # port: 25 + # username: + # password: mail: - host: localhost - port: 25 - username: - password: + host: smtp.mailersend.net + port: 587 + username: MS_hwQpFm@trial-k68zxl2o29egj905.mlsender.net + password: zTuZ0pxazgHfOWPK + properties: + mail: + smtp: + auth: true + starttls: + enable: true + required: true messages: cache-duration: PT1S # 1 second, see the ISO 8601 standard thymeleaf: diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 7ba3ab5..71e02ab 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -62,7 +62,7 @@ management: enabled: true health: mail: - enabled: false # When using the MailService, configure an SMTP server and set this to true + enabled: true # When using the MailService, configure an SMTP server and set this to true prometheus: metrics: export: diff --git a/src/main/webapp/app/entities/activity/activity-update.tsx b/src/main/webapp/app/entities/activity/activity-update.tsx index 2c705e8..1a71fbc 100644 --- a/src/main/webapp/app/entities/activity/activity-update.tsx +++ b/src/main/webapp/app/entities/activity/activity-update.tsx @@ -130,30 +130,30 @@ export const ActivityUpdate = () => { }} /> - - - - + {/* */} + {/* */} + {/* */} + {/* */} test title, http://127.0.0.1:8080, john