DONE: add customer pages, implement auth on teller page
This commit is contained in:
@@ -10,7 +10,6 @@ import ba.unsa.etf.si.bbqms.ticket_service.api.TicketService;
|
||||
import ba.unsa.etf.si.bbqms.ws.models.DisplayDto;
|
||||
import ba.unsa.etf.si.bbqms.ws.models.ErrorResponseDto;
|
||||
import ba.unsa.etf.si.bbqms.ws.models.ServiceDto;
|
||||
import ba.unsa.etf.si.bbqms.ws.models.ServiceResponseDto;
|
||||
import ba.unsa.etf.si.bbqms.ws.models.TicketDto;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -28,8 +27,8 @@ public class TellerStationController {
|
||||
private final TicketService ticketService;
|
||||
|
||||
public TellerStationController(final StationService stationService,
|
||||
final AuthService authService,
|
||||
final TicketService ticketService) {
|
||||
final AuthService authService,
|
||||
final TicketService ticketService) {
|
||||
this.stationService = stationService;
|
||||
this.authService = authService;
|
||||
this.ticketService = ticketService;
|
||||
@@ -37,7 +36,7 @@ public class TellerStationController {
|
||||
|
||||
@GetMapping("/{tenantCode}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity getAll(@PathVariable final String tenantCode){
|
||||
public ResponseEntity getAll(@PathVariable final String tenantCode) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
@@ -56,43 +55,45 @@ public class TellerStationController {
|
||||
@GetMapping("/{tenantCode}/{stationId}/services")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity getServices(@PathVariable final String tenantCode,
|
||||
@PathVariable final String stationId,
|
||||
@RequestParam(defaultValue = "true") final boolean assigned) {
|
||||
@PathVariable final String stationId,
|
||||
@RequestParam(defaultValue = "true") final boolean assigned) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
try {
|
||||
final Set<Service> serviceSet = this.stationService.getServicesByAssigned(Long.parseLong(stationId),assigned);
|
||||
final Set<ServiceResponseDto> serviceResponseDtoSet = serviceSet.stream()
|
||||
.map(ServiceResponseDto::fromEntity)
|
||||
final Set<Service> serviceSet = this.stationService.getServicesByAssigned(Long.parseLong(stationId),
|
||||
assigned);
|
||||
final Set<ServiceDto> serviceDtoSet = serviceSet.stream()
|
||||
.map(ServiceDto::fromEntity)
|
||||
.collect(Collectors.toSet());
|
||||
return ResponseEntity.ok().body(serviceResponseDtoSet);
|
||||
}
|
||||
catch (final Exception e) {
|
||||
return ResponseEntity.ok().body(serviceDtoSet);
|
||||
} catch (final Exception e) {
|
||||
return ResponseEntity.badRequest().body(new ErrorResponseDto(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/{tenantCode}/{stationId}/services/assignable")
|
||||
public ResponseEntity findAssignableServices(@PathVariable final String stationId,
|
||||
@PathVariable final String tenantCode) {
|
||||
@PathVariable final String tenantCode) {
|
||||
return ResponseEntity.ok().body(
|
||||
this.stationService.findAssignableServices(Long.parseLong(stationId))
|
||||
);
|
||||
this.stationService.findAssignableServices(Long.parseLong(stationId)).stream()
|
||||
.map(ServiceDto::fromEntity)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@PutMapping("/{tenantCode}/{stationId}/services/{serviceId}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity addTellerStationService(@PathVariable final String tenantCode,
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String serviceId) {
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String serviceId) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
try {
|
||||
final TellerStation updatedTellerStation = this.stationService.addTellerStationService(Long.parseLong(stationId), Long.parseLong(serviceId));
|
||||
final TellerStation updatedTellerStation = this.stationService
|
||||
.addTellerStationService(Long.parseLong(stationId), Long.parseLong(serviceId));
|
||||
return ResponseEntity.ok().body(TellerStationResponseDto.fromEntity(updatedTellerStation));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
@@ -102,14 +103,15 @@ public class TellerStationController {
|
||||
@DeleteMapping("/{tenantCode}/{stationId}/services/{serviceId}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity deleteTellerStationService(@PathVariable final String tenantCode,
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String serviceId) {
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String serviceId) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
try {
|
||||
final TellerStation updatedTellerStation = this.stationService.deleteTellerStationService(Long.parseLong(stationId), Long.parseLong(serviceId));
|
||||
final TellerStation updatedTellerStation = this.stationService
|
||||
.deleteTellerStationService(Long.parseLong(stationId), Long.parseLong(serviceId));
|
||||
return ResponseEntity.ok().body(TellerStationResponseDto.fromEntity(updatedTellerStation));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.badRequest().body(new ErrorResponseDto(e.getMessage()));
|
||||
@@ -119,16 +121,17 @@ public class TellerStationController {
|
||||
@PutMapping("/{tenantCode}/{stationId}/displays/{displayId}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity addDisplayToStation(@PathVariable final String tenantCode,
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String displayId) {
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String displayId) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
try {
|
||||
final TellerStation updatedTellerStation = this.stationService.addTellerStationDisplay(Long.parseLong(stationId), Long.parseLong(displayId));
|
||||
final TellerStation updatedTellerStation = this.stationService
|
||||
.addTellerStationDisplay(Long.parseLong(stationId), Long.parseLong(displayId));
|
||||
return ResponseEntity.ok().body(TellerStationResponseDto.fromEntity(updatedTellerStation));
|
||||
} catch(final Exception exception) {
|
||||
} catch (final Exception exception) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
}
|
||||
@@ -136,29 +139,29 @@ public class TellerStationController {
|
||||
@DeleteMapping("/{tenantCode}/{stationId}/displays/{displayId}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_BRANCH_ADMIN')")
|
||||
public ResponseEntity removeDisplayFromStation(@PathVariable final String tenantCode,
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String displayId) {
|
||||
@PathVariable final String stationId,
|
||||
@PathVariable final String displayId) {
|
||||
if (!this.authService.canChangeTenant(tenantCode)) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
try {
|
||||
final TellerStation updatedTellerStation = this.stationService.deleteTellerStationDisplay(Long.parseLong(stationId), Long.parseLong(displayId));
|
||||
final TellerStation updatedTellerStation = this.stationService
|
||||
.deleteTellerStationDisplay(Long.parseLong(stationId), Long.parseLong(displayId));
|
||||
return ResponseEntity.ok().body(TellerStationResponseDto.fromEntity(updatedTellerStation));
|
||||
} catch(final Exception exception) {
|
||||
} catch (final Exception exception) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/{tenantCode}/{branchId}")
|
||||
public ResponseEntity getBranchStations(@PathVariable final String tenantCode,
|
||||
@PathVariable final String branchId) {
|
||||
try{
|
||||
@PathVariable final String branchId) {
|
||||
try {
|
||||
return ResponseEntity.ok().body(
|
||||
this.stationService.getAllByBranch(Long.parseLong(branchId)).stream()
|
||||
.map(TellerStationResponseDto::fromEntity)
|
||||
.toList()
|
||||
);
|
||||
.toList());
|
||||
} catch (final Exception exception) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
@@ -168,7 +171,8 @@ public class TellerStationController {
|
||||
public ResponseEntity getTicketsForTellerStation(@PathVariable final long stationId) {
|
||||
try {
|
||||
final List<TicketDto> ticketDtos = this.ticketService.findWithStation(stationId).stream()
|
||||
.filter(ticket -> ticket.getTellerStation() == null || ticket.getTellerStation().getId() == stationId)
|
||||
.filter(ticket -> ticket.getTellerStation() == null
|
||||
|| ticket.getTellerStation().getId() == stationId)
|
||||
.map(TicketDto::fromEntity)
|
||||
.toList();
|
||||
|
||||
@@ -178,15 +182,14 @@ public class TellerStationController {
|
||||
}
|
||||
}
|
||||
|
||||
public record TellerStationResponseDto(long id, String name, DisplayDto display, Set<ServiceResponseDto> services) {
|
||||
public record TellerStationResponseDto(long id, String name, DisplayDto display, Set<ServiceDto> services) {
|
||||
public static TellerStationResponseDto fromEntity(final TellerStation tellerStation) {
|
||||
final Set<Service> serviceSet = tellerStation.getServices();
|
||||
return new TellerStationResponseDto(
|
||||
tellerStation.getId(),
|
||||
tellerStation.getName(),
|
||||
tellerStation.getDisplay() != null ? DisplayDto.fromEntity(tellerStation.getDisplay()) : null,
|
||||
serviceSet.stream().map(ServiceResponseDto::fromEntity).collect(Collectors.toSet())
|
||||
);
|
||||
serviceSet.stream().map(ServiceDto::fromEntity).collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ public class TenantController {
|
||||
private final AuthService authService;
|
||||
|
||||
public TenantController(final TenantService tenantService,
|
||||
final BranchService branchService,
|
||||
final GroupService groupService,
|
||||
final AuthService authService) {
|
||||
final BranchService branchService,
|
||||
final GroupService groupService,
|
||||
final AuthService authService) {
|
||||
this.tenantService = tenantService;
|
||||
this.branchService = branchService;
|
||||
this.groupService = groupService;
|
||||
@@ -57,7 +57,8 @@ public class TenantController {
|
||||
|
||||
@PutMapping("/{code}")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity updateTenant(@PathVariable final String code, @RequestBody final TenantDto request) throws Exception {
|
||||
public ResponseEntity updateTenant(@PathVariable final String code, @RequestBody final TenantDto request)
|
||||
throws Exception {
|
||||
if (!this.authService.canChangeTenant(code)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
@@ -71,7 +72,8 @@ public class TenantController {
|
||||
|
||||
@PostMapping("/{code}/services")
|
||||
@PreAuthorize("hasAnyRole('ROLE_BRANCH_ADMIN', 'ROLE_SUPER_ADMIN')")
|
||||
public ResponseEntity addService(@PathVariable(name = "code") final String code, @RequestBody final ServiceRequestDto serviceRequestDto) {
|
||||
public ResponseEntity addService(@PathVariable(name = "code") final String code,
|
||||
@RequestBody final ServiceRequestDto serviceRequestDto) {
|
||||
if (!this.authService.canChangeTenant(code)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
@@ -92,7 +94,8 @@ public class TenantController {
|
||||
}
|
||||
|
||||
@GetMapping("/{code}/services/group/{groupId}")
|
||||
public ResponseEntity listGroupAssignableServices(@PathVariable final String code, @PathVariable final String groupId) {
|
||||
public ResponseEntity listGroupAssignableServices(@PathVariable final String code,
|
||||
@PathVariable final String groupId) {
|
||||
final List<Service> possibleServices = this.tenantService.getAllServicesByTenant(code);
|
||||
final List<Service> assignedServices = this.groupService.get(Long.parseLong(groupId))
|
||||
.getServices().stream().toList();
|
||||
@@ -105,8 +108,8 @@ public class TenantController {
|
||||
@PutMapping("/{code}/services/{id}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_BRANCH_ADMIN', 'ROLE_SUPER_ADMIN')")
|
||||
public ResponseEntity updateService(@PathVariable(name = "code") final String code,
|
||||
@PathVariable(name = "id") final Long id,
|
||||
@RequestBody final ServiceRequestDto request) {
|
||||
@PathVariable(name = "id") final Long id,
|
||||
@RequestBody final ServiceRequestDto request) {
|
||||
if (!this.authService.canChangeTenant(code)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
@@ -120,7 +123,8 @@ public class TenantController {
|
||||
|
||||
@DeleteMapping("/{code}/services/{id}")
|
||||
@PreAuthorize("hasAnyRole('ROLE_BRANCH_ADMIN', 'ROLE_SUPER_ADMIN')")
|
||||
public ResponseEntity deleteService(@PathVariable(name = "code") final String code, @PathVariable(name = "id") final Long id) {
|
||||
public ResponseEntity deleteService(@PathVariable(name = "code") final String code,
|
||||
@PathVariable(name = "id") final Long id) {
|
||||
if (!this.authService.canChangeTenant(code)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
@@ -22,24 +22,25 @@ import ManageDisplays from './pages/ManageDisplays/ManageDisplays';
|
||||
import ManageUsers from './pages/UserManagingScreen/UserManagingScreen';
|
||||
import ViewQueues from './pages/ViewBranchQueues/ViewBranchQueues';
|
||||
import { ROLES } from './constants.js';
|
||||
import { clearSession, getToken, getUserData } from './utils/session.js';
|
||||
|
||||
export default function App() {
|
||||
const [user, setUser] = useState();
|
||||
/*
|
||||
Kada se logiramo, ako vec postoji token u localStorage, provjerimo da li je validan (nije istekao)
|
||||
Ako je validan, ulogujemo usera, ako nije ocistimo storage od starih podataka
|
||||
Kada se logiramo, ako vec postoji token u cookie-u, provjerimo da li je validan (nije istekao)
|
||||
Ako je validan, ulogujemo usera, ako nije ocistimo session
|
||||
*/
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
const url = `${ SERVER_URL }/api/v1/auth`;
|
||||
const url = `${SERVER_URL}/api/v1/auth`;
|
||||
fetchData(url, 'GET')
|
||||
.then(({ data, success }) => {
|
||||
.then(({ success }) => {
|
||||
if (success) {
|
||||
setUser(JSON.parse(localStorage.getItem('userData')));
|
||||
setUser(getUserData());
|
||||
} else {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('userData');
|
||||
clearSession();
|
||||
setUser(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -47,152 +48,152 @@ export default function App() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<UserContext.Provider value={ { user, setUser } }>
|
||||
<UserContext.Provider value={{ user, setUser }}>
|
||||
<Header />
|
||||
<Routes>
|
||||
<Route exact path="/:tenantCode/manage/displays" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageDisplays />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
<Route exact path="/:tenantCode/manage/stations" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageStations />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
<Route exact path="/:tenantCode/manage/groups" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageGroups />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
|
||||
<Route exact path="/:tenantCode/manage/branches" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageBranches />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
|
||||
<Route exact path="/:tenantCode/companydetails"
|
||||
element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<CompanyInfoUpdate />
|
||||
</AuthGuard>
|
||||
}
|
||||
element={
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<CompanyInfoUpdate />
|
||||
</AuthGuard>
|
||||
}
|
||||
/>
|
||||
<Route exact path="/:tenantCode/manage/services" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageServices />
|
||||
</AuthGuard> }
|
||||
</AuthGuard>}
|
||||
/>
|
||||
<Route exact path="/:tenantCode/manage/users" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ManageUsers />
|
||||
</AuthGuard>
|
||||
} />
|
||||
<Route exact path="/login" element={ <LoginScreen /> } />
|
||||
<Route exact path="/login" element={<LoginScreen />} />
|
||||
<Route exact path="/:tenantCode/manage/admins" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN]}>
|
||||
<ManageAdmins />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
<Route exact path="/profile" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<AdminProfile />
|
||||
</AuthGuard> } />
|
||||
<Route exact path="/" element={ <LoginScreen /> } />
|
||||
</AuthGuard>} />
|
||||
<Route exact path="/" element={<LoginScreen />} />
|
||||
<Route exact path="/loginauth"
|
||||
element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<LoginAuth />
|
||||
</AuthGuard>
|
||||
}
|
||||
element={
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<LoginAuth />
|
||||
</AuthGuard>
|
||||
}
|
||||
/>
|
||||
<Route exact path="/:tenantCode/queues" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<ViewQueues />
|
||||
</AuthGuard> } />
|
||||
</AuthGuard>} />
|
||||
|
||||
<Route exact path="/:tenantCode/home" element={
|
||||
<AuthGuard roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<AuthGuard roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<HomePage></HomePage>
|
||||
<CanAccess roles={ [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
<CanAccess roles={[ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
<>
|
||||
{ user && (
|
||||
{user && (
|
||||
<>
|
||||
<HomePageCard
|
||||
title="Manage displays"
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/displays` }
|
||||
url={`/${user.tenantCode}/manage/displays`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="Manage groups"
|
||||
backgroundColor="var(--light-blue)"
|
||||
buttonColor="var(--dark-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/groups` }
|
||||
url={`/${user.tenantCode}/manage/groups`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="Manage branches"
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/branches` }
|
||||
url={`/${user.tenantCode}/manage/branches`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="Manage services"
|
||||
backgroundColor="var(--light-blue)"
|
||||
buttonColor="var(--dark-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/services` }
|
||||
url={`/${user.tenantCode}/manage/services`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="Manage teller stations"
|
||||
backgroundColor="var(--light-blue)"
|
||||
buttonColor="var(--dark-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/stations` }
|
||||
url={`/${user.tenantCode}/manage/stations`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="Manage company details"
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={ `/${ user.tenantCode }/companydetails` }
|
||||
url={`/${user.tenantCode}/companydetails`}
|
||||
/>
|
||||
<HomePageCard
|
||||
title="View queues"
|
||||
backgroundColor="var(--light-blue)"
|
||||
buttonColor="var(--dark-blue)"
|
||||
url={ `/${ user.tenantCode }/queues` }
|
||||
url={`/${user.tenantCode}/queues`}
|
||||
/>
|
||||
</>
|
||||
) }
|
||||
)}
|
||||
</>
|
||||
</CanAccess>
|
||||
|
||||
<CanAccess roles={ [ROLES.ROLE_SUPER_ADMIN] }>
|
||||
<CanAccess roles={[ROLES.ROLE_SUPER_ADMIN]}>
|
||||
<>
|
||||
{ user && (
|
||||
{user && (
|
||||
<>
|
||||
<HomePageCard title="Manage administrators"
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/admins` }></HomePageCard>
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={`/${user.tenantCode}/manage/admins`}></HomePageCard>
|
||||
<HomePageCard
|
||||
title="Manage users"
|
||||
title="Manage Teller"
|
||||
backgroundColor="var(--light-blue)"
|
||||
buttonColor="var(--dark-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/users` }
|
||||
url={`/${user.tenantCode}/manage/users`}
|
||||
/>
|
||||
</>
|
||||
) }
|
||||
)}
|
||||
</>
|
||||
</CanAccess>
|
||||
|
||||
<CanAccess roles={ [ROLES.ROLE_BRANCH_ADMIN] }>
|
||||
{ user && (
|
||||
<CanAccess roles={[ROLES.ROLE_BRANCH_ADMIN]}>
|
||||
{user && (
|
||||
<HomePageCard
|
||||
title="Manage users"
|
||||
backgroundColor="var(--dark-blue)"
|
||||
buttonColor="var(--light-blue)"
|
||||
url={ `/${ user.tenantCode }/manage/users` }
|
||||
url={`/${user.tenantCode}/manage/users`}
|
||||
/>
|
||||
) }
|
||||
)}
|
||||
</CanAccess>
|
||||
</AuthGuard>
|
||||
} />
|
||||
<Route path="*" element={ <NotFound /> } />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</UserContext.Provider>
|
||||
</>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { getUserData } from '../../utils/session.js';
|
||||
|
||||
export default function AuthGuard({ children, roles }) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const storedUserData = localStorage.getItem('userData');
|
||||
const user = storedUserData ? JSON.parse(storedUserData) : null;
|
||||
const user = getUserData();
|
||||
|
||||
if (!user) {
|
||||
navigate('/login');
|
||||
@@ -23,7 +23,7 @@ export default function AuthGuard({ children, roles }) {
|
||||
|
||||
return (
|
||||
<>
|
||||
{ children }
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -6,16 +6,16 @@ import profileImage from '../../../assets/profile-user.png'
|
||||
|
||||
import './Header.css';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { clearSession } from '../../utils/session.js';
|
||||
|
||||
export default function Header() {
|
||||
const navigate = useNavigate();
|
||||
const { user, setUser } = useContext(UserContext);
|
||||
|
||||
function handleLogout() {
|
||||
localStorage.removeItem('userData');
|
||||
localStorage.removeItem('token');
|
||||
clearSession();
|
||||
setUser(null);
|
||||
navigate('/');
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
const path = window.location.pathname;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { SERVER_URL } from "../../constants.js";
|
||||
import { fetchData } from '../../fetching/Fetch.js';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { getUserData, setSession } from '../../utils/session.js';
|
||||
|
||||
function doSubmit(submittedValues) {
|
||||
console.log(`Submitted: ${submittedValues.join("")}`);
|
||||
@@ -126,10 +127,9 @@ export default function LoginAuth() {
|
||||
dispatch({ type: "VERIFY" });
|
||||
|
||||
try {
|
||||
const storedUserData = localStorage.getItem('userData');
|
||||
const userData = storedUserData ? JSON.parse(storedUserData) : null;
|
||||
const userData = getUserData();
|
||||
if (!userData) {
|
||||
throw new Error("Email not found in localStorage");
|
||||
throw new Error("Email not found in session");
|
||||
}
|
||||
|
||||
const url = `${ SERVER_URL }/api/v1/auth/tfa`;
|
||||
@@ -139,7 +139,11 @@ export default function LoginAuth() {
|
||||
});
|
||||
|
||||
if (success) {
|
||||
localStorage.setItem('token', data.token);
|
||||
setSession({
|
||||
token: data.token,
|
||||
userData: data.userData,
|
||||
isTfa: true,
|
||||
});
|
||||
setUser(data.userData);
|
||||
navigate(`/${ data.userData.tenantCode }/home`);
|
||||
} else {
|
||||
|
||||
@@ -5,6 +5,7 @@ import "./LoginForm.css";
|
||||
import LoginAuth from "../LoginAuth/LoginAuth";
|
||||
import { Route, Routes, useNavigate, Link } from "react-router-dom";
|
||||
import { SERVER_URL } from "../../constants.js";
|
||||
import { setSession } from "../../utils/session.js";
|
||||
|
||||
const LoginForm = () => {
|
||||
const [username, setUsername] = useState("");
|
||||
@@ -28,7 +29,11 @@ const LoginForm = () => {
|
||||
return;
|
||||
}
|
||||
const data = await response.json();
|
||||
localStorage.setItem('userData', JSON.stringify(data));
|
||||
setSession({
|
||||
userData: data.userData ?? data,
|
||||
token: data.token,
|
||||
isTfa: !data.token,
|
||||
});
|
||||
navigate('/');
|
||||
}
|
||||
|
||||
@@ -67,9 +72,12 @@ const LoginForm = () => {
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
localStorage.setItem('userData', JSON.stringify(data));
|
||||
|
||||
if (response.ok) {
|
||||
setSession({
|
||||
userData: data.userData ?? data,
|
||||
token: data.token,
|
||||
isTfa: !data.token,
|
||||
});
|
||||
setIsSubmitted(true);
|
||||
navigate('/');
|
||||
} else if (response.status === 403) {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/*
|
||||
Koristiti ovu funkciju za fetchanje u buducnosti kad god je to moguce.
|
||||
*/
|
||||
import { getToken, setToken } from '../utils/session.js';
|
||||
|
||||
export async function fetchData(url, method, body) {
|
||||
const headers = new Headers();
|
||||
|
||||
const token = localStorage.getItem('token');
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
headers.append('Authorization', `Bearer ${ token }`);
|
||||
}
|
||||
@@ -27,9 +29,9 @@ export async function fetchData(url, method, body) {
|
||||
//na svaki ispravan rezultat treba da dobijemo novi token da refreshamo stari
|
||||
const newToken = res.headers.get('Auth-Token');
|
||||
if (newToken) {
|
||||
localStorage.setItem('token', newToken);
|
||||
setToken(newToken);
|
||||
}
|
||||
}
|
||||
|
||||
return { data: data, success: res.ok };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import { SERVER_URL } from '../../constants.js';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { getToken } from '../../utils/session.js';
|
||||
|
||||
const styles = {
|
||||
primaryButton: {
|
||||
@@ -30,22 +31,22 @@ const AdminManageScreen = () => {
|
||||
const [adminEmail, setAdminEmail] = useState('');
|
||||
const [adminPassword, setAdminPassword] = useState('');
|
||||
const [selectedAdminIndex, setSelectedAdminIndex] = useState(null);
|
||||
const [token, setToken] = useState('');
|
||||
const [emailError, setEmailError] = useState('');
|
||||
const [passwordError, setPasswordError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem('token');
|
||||
if (storedToken) {
|
||||
setToken(storedToken);
|
||||
if (getToken()) {
|
||||
fetchAdmins();
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
fetchAdmins();
|
||||
}
|
||||
}, [token]);
|
||||
const authHeaders = () => {
|
||||
const token = getToken();
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
const fetchAdmins = async () => {
|
||||
try {
|
||||
@@ -54,10 +55,7 @@ const AdminManageScreen = () => {
|
||||
});
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: requestBody
|
||||
});
|
||||
|
||||
@@ -87,10 +85,7 @@ const AdminManageScreen = () => {
|
||||
try {
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify(requestBody)
|
||||
});
|
||||
|
||||
@@ -122,10 +117,7 @@ const AdminManageScreen = () => {
|
||||
};
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user/${admins[selectedAdminIndex].id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify(updatedAdmin),
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -146,10 +138,7 @@ const AdminManageScreen = () => {
|
||||
try {
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user/${userId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
}
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (response.ok) {
|
||||
const updatedAdmins = admins.filter(admin => admin.id !== userId);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { fetchData } from '../../fetching/Fetch.js';
|
||||
import { SERVER_URL } from '../../constants';
|
||||
import { getIsTfa, getUserData, setIsTfa } from '../../utils/session.js';
|
||||
import "./AdminProfile.css"
|
||||
|
||||
export default function AdminProfile(){
|
||||
@@ -10,12 +11,9 @@ export default function AdminProfile(){
|
||||
const [userData, setUserData] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const storedUserData = localStorage.getItem('userData');
|
||||
setUserData(JSON.parse(storedUserData));
|
||||
|
||||
const storedIsTfa = localStorage.getItem('isTfa');
|
||||
let isTfa = JSON.parse(storedIsTfa);
|
||||
setUserData(getUserData());
|
||||
|
||||
const isTfa = getIsTfa();
|
||||
setIsChecked(isTfa);
|
||||
setIsQRCodeEnabled(isTfa);
|
||||
}, []);
|
||||
@@ -25,7 +23,7 @@ export default function AdminProfile(){
|
||||
const { data, success } = await fetchData(url, 'PUT', {
|
||||
isTfa: isChecked
|
||||
});
|
||||
localStorage.setItem('isTfa', isChecked);
|
||||
setIsTfa(isChecked);
|
||||
setIsQRCodeEnabled(isChecked);
|
||||
if(!isChecked){
|
||||
setQrCodeSrc('');
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import React, { useContext, useState } from 'react';
|
||||
import validator from 'validator';
|
||||
import './LoginScreen.css';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { SERVER_URL } from '../../constants.js';
|
||||
import { ROLES, SERVER_URL } from '../../constants.js';
|
||||
import { fetchData } from '../../fetching/Fetch.js';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { clearSession, setSession } from '../../utils/session.js';
|
||||
|
||||
const ADMIN_ROLES = [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN];
|
||||
|
||||
function hasAdminAccess(userData) {
|
||||
const roles = Array.isArray(userData?.roles) ? userData.roles : [];
|
||||
return roles.some((role) => ADMIN_ROLES.includes(role));
|
||||
}
|
||||
|
||||
export default function LoginScreen() {
|
||||
const navigate = useNavigate();
|
||||
const { setUser } = useContext(UserContext);
|
||||
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
@@ -38,26 +47,42 @@ export default function LoginScreen() {
|
||||
password: password
|
||||
});
|
||||
|
||||
if (success) {
|
||||
if (data.userData == undefined) {
|
||||
localStorage.setItem('userData', JSON.stringify(data));
|
||||
} else {
|
||||
localStorage.setItem('userData', JSON.stringify(data.userData));
|
||||
localStorage.setItem('token', data.token);
|
||||
setUser(data.userData);
|
||||
}
|
||||
setIsSubmitted(true);
|
||||
|
||||
if (data.token) {
|
||||
localStorage.setItem('isTfa', false);
|
||||
navigate(`/${data.userData.tenantCode}/home`);
|
||||
} else {
|
||||
localStorage.setItem('isTfa', true);
|
||||
navigate('/loginauth');
|
||||
}
|
||||
} else {
|
||||
if (!success || !data) {
|
||||
setError('Your credentials are incorrect.');
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = data.userData ?? data;
|
||||
const token = data.token;
|
||||
|
||||
if (!hasAdminAccess(userData)) {
|
||||
clearSession();
|
||||
setUser(null);
|
||||
setError(
|
||||
'This account is a regular user (ROLE_USER) and cannot access the admin app. Create an admin via Manage administrators.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
setSession({ userData, isTfa: true });
|
||||
setUser(userData);
|
||||
navigate('/loginauth', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!userData?.tenantCode) {
|
||||
setError('Login succeeded but tenant information is missing.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSession({
|
||||
userData,
|
||||
token,
|
||||
isTfa: false,
|
||||
});
|
||||
setUser(userData);
|
||||
navigate(`/${userData.tenantCode}/home`, { replace: true });
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
setError('An error occurred. Please try again.');
|
||||
@@ -73,11 +98,6 @@ export default function LoginScreen() {
|
||||
setPassword(event.target.value);
|
||||
setError('');
|
||||
};
|
||||
/*
|
||||
if (isSubmitted) {
|
||||
//navigate('/loginAuth');
|
||||
navigate('/companydetails');
|
||||
}*/
|
||||
|
||||
return (
|
||||
<div id="login-form">
|
||||
@@ -92,9 +112,7 @@ export default function LoginScreen() {
|
||||
value={username}
|
||||
onChange={handleUsernameChange}
|
||||
/>
|
||||
{error && (error.includes('Username') || error.includes('Invalid')) &&
|
||||
<p className="error">{error}</p>}
|
||||
{error && (error.includes('credentials')) && <p className="error">{error}</p>}
|
||||
{error && !error.includes('Password') && <p className="error">{error}</p>}
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="password">Password:</label>
|
||||
@@ -116,4 +134,4 @@ export default function LoginScreen() {
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,8 +2,8 @@ import React, { useState, useEffect } from 'react';
|
||||
import { Button, Table, Modal, Form } from 'react-bootstrap';
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import { SERVER_URL } from '../../constants.js';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { getToken } from '../../utils/session.js';
|
||||
|
||||
const styles = {
|
||||
primaryButton: {
|
||||
@@ -29,34 +29,31 @@ const UserManageScreen = () => {
|
||||
const [userEmail, setUserEmail] = useState('');
|
||||
const [userPassword, setUserPassword] = useState('');
|
||||
const [selectedUserIndex, setSelectedUserIndex] = useState(null);
|
||||
const [token, setToken] = useState('');
|
||||
const [emailError, setEmailError] = useState('');
|
||||
const [passwordError, setPasswordError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem('token');
|
||||
if (storedToken) {
|
||||
setToken(storedToken);
|
||||
if (getToken()) {
|
||||
fetchUsers();
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
fetchUsers();
|
||||
}
|
||||
}, [token]);
|
||||
const authHeaders = () => {
|
||||
const token = getToken();
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const requestBody = JSON.stringify({
|
||||
roleName: 'ROLE_USER'
|
||||
});
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}`, {
|
||||
const response = await fetch(`${SERVER_URL}/api/v1/admin/${tenantCode}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: requestBody
|
||||
});
|
||||
|
||||
@@ -84,12 +81,9 @@ const UserManageScreen = () => {
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user`, {
|
||||
const response = await fetch(`${SERVER_URL}/api/v1/admin/${tenantCode}/user`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify(requestBody)
|
||||
});
|
||||
|
||||
@@ -119,12 +113,9 @@ const UserManageScreen = () => {
|
||||
const updatedUser = {
|
||||
email: userEmail
|
||||
};
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user/${users[selectedUserIndex].id}`, {
|
||||
const response = await fetch(`${SERVER_URL}/api/v1/admin/${tenantCode}/user/${users[selectedUserIndex].id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
},
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify(updatedUser),
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -144,12 +135,9 @@ const UserManageScreen = () => {
|
||||
|
||||
const handleDeleteUser = async (userId) => {
|
||||
try {
|
||||
const response = await fetch(`${ SERVER_URL }/api/v1/admin/${tenantCode}/user/${userId}`, {
|
||||
const response = await fetch(`${SERVER_URL}/api/v1/admin/${tenantCode}/user/${userId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token
|
||||
}
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (response.ok) {
|
||||
const updatedUsers = users.filter(user => user.id !== userId);
|
||||
@@ -171,28 +159,32 @@ const UserManageScreen = () => {
|
||||
|
||||
return (
|
||||
<div className="text-center">
|
||||
<h2>Manage Users</h2>
|
||||
<h2>Manage Teller</h2>
|
||||
<p className="text-muted mb-3">
|
||||
These accounts have ROLE_USER and cannot log into the admin app.
|
||||
Use Manage administrators to create admin logins.
|
||||
</p>
|
||||
<Button variant="primary" style={styles.primaryButton} className="mb-3" onClick={() => { setShowModal(true); setSelectedUserIndex(null); }}>Add User</Button>
|
||||
|
||||
<Table striped bordered hover>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Email</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Email</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user, index) => (
|
||||
<tr key={index}>
|
||||
<td>{user.id}</td>
|
||||
<td>{user.email}</td>
|
||||
<td>
|
||||
<Button variant="info" style={styles.infoButton} onClick={() => handleEditClick(index)}>Edit</Button>{' '}
|
||||
<Button variant="danger" onClick={() => handleDeleteUser(user.id)}>Delete</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{users.map((user, index) => (
|
||||
<tr key={index}>
|
||||
<td>{user.id}</td>
|
||||
<td>{user.email}</td>
|
||||
<td>
|
||||
<Button variant="info" style={styles.infoButton} onClick={() => handleEditClick(index)}>Edit</Button>{' '}
|
||||
<Button variant="danger" onClick={() => handleDeleteUser(user.id)}>Delete</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
const TOKEN_KEY = 'token';
|
||||
const USER_DATA_KEY = 'userData';
|
||||
const IS_TFA_KEY = 'isTfa';
|
||||
|
||||
/** Matches backend jwt.token-validity-time (PT30M). */
|
||||
const SESSION_MAX_AGE_SECONDS = 30 * 60;
|
||||
|
||||
function getCookie(name) {
|
||||
const prefix = `${encodeURIComponent(name)}=`;
|
||||
const parts = document.cookie ? document.cookie.split('; ') : [];
|
||||
|
||||
for (const part of parts) {
|
||||
if (part.startsWith(prefix)) {
|
||||
return decodeURIComponent(part.slice(prefix.length));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function setCookie(name, value, maxAgeSeconds = SESSION_MAX_AGE_SECONDS) {
|
||||
const secure = window.location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = [
|
||||
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
|
||||
`Path=/`,
|
||||
`Max-Age=${maxAgeSeconds}`,
|
||||
`SameSite=Lax`,
|
||||
secure,
|
||||
].join('; ');
|
||||
}
|
||||
|
||||
function removeCookie(name) {
|
||||
document.cookie = `${encodeURIComponent(name)}=; Path=/; Max-Age=0; SameSite=Lax`;
|
||||
}
|
||||
|
||||
function migrateFromLocalStorage(key) {
|
||||
const legacy = localStorage.getItem(key);
|
||||
if (legacy == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
setCookie(key, legacy);
|
||||
localStorage.removeItem(key);
|
||||
return legacy;
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return getCookie(TOKEN_KEY) ?? migrateFromLocalStorage(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setToken(token) {
|
||||
if (token == null || token === '') {
|
||||
removeCookie(TOKEN_KEY);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
setCookie(TOKEN_KEY, token);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getUserData() {
|
||||
const raw = getCookie(USER_DATA_KEY) ?? migrateFromLocalStorage(USER_DATA_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
removeCookie(USER_DATA_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setUserData(userData) {
|
||||
if (userData == null) {
|
||||
removeCookie(USER_DATA_KEY);
|
||||
localStorage.removeItem(USER_DATA_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
setCookie(USER_DATA_KEY, JSON.stringify(userData));
|
||||
localStorage.removeItem(USER_DATA_KEY);
|
||||
}
|
||||
|
||||
export function getIsTfa() {
|
||||
const raw = getCookie(IS_TFA_KEY) ?? migrateFromLocalStorage(IS_TFA_KEY);
|
||||
if (raw == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return raw === 'true';
|
||||
}
|
||||
}
|
||||
|
||||
export function setIsTfa(isTfa) {
|
||||
setCookie(IS_TFA_KEY, JSON.stringify(Boolean(isTfa)));
|
||||
localStorage.removeItem(IS_TFA_KEY);
|
||||
}
|
||||
|
||||
export function setSession({ token, userData, isTfa } = {}) {
|
||||
if (token !== undefined) {
|
||||
setToken(token);
|
||||
}
|
||||
if (userData !== undefined) {
|
||||
setUserData(userData);
|
||||
}
|
||||
if (isTfa !== undefined) {
|
||||
setIsTfa(isTfa);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
removeCookie(TOKEN_KEY);
|
||||
removeCookie(USER_DATA_KEY);
|
||||
removeCookie(IS_TFA_KEY);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_DATA_KEY);
|
||||
localStorage.removeItem(IS_TFA_KEY);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -0,0 +1,5 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,24 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #fafafa;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Customer Queue",
|
||||
description: "Take a queue ticket for your branch and service",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import CustomerTicketFlow from "@/components/CustomerTicketFlow";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex min-h-full flex-1 flex-col bg-zinc-50">
|
||||
<CustomerTicketFlow />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import {
|
||||
Branch,
|
||||
Service,
|
||||
Tenant,
|
||||
Ticket,
|
||||
createTicket,
|
||||
getBranchServices,
|
||||
getBranches,
|
||||
getTenant,
|
||||
} from "@/lib/api";
|
||||
import { getDeviceToken } from "@/lib/device";
|
||||
|
||||
type Step = "tenant" | "branch" | "service" | "ticket";
|
||||
|
||||
export default function CustomerTicketFlow() {
|
||||
const [step, setStep] = useState<Step>("tenant");
|
||||
const [tenantCode, setTenantCode] = useState("DFLT");
|
||||
const [tenant, setTenant] = useState<Tenant | null>(null);
|
||||
const [branches, setBranches] = useState<Branch[]>([]);
|
||||
const [services, setServices] = useState<Service[]>([]);
|
||||
const [selectedBranch, setSelectedBranch] = useState<Branch | null>(null);
|
||||
const [ticket, setTicket] = useState<Ticket | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleTenantSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const code = tenantCode.trim().toUpperCase();
|
||||
if (!code) {
|
||||
setError("Enter a company code.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [tenantData, branchData] = await Promise.all([
|
||||
getTenant(code),
|
||||
getBranches(code),
|
||||
]);
|
||||
setTenant(tenantData);
|
||||
setBranches(branchData);
|
||||
setTenantCode(code);
|
||||
setStep("branch");
|
||||
} catch {
|
||||
setError("Could not find that company. Check the code and try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSelectBranch(branch: Branch) {
|
||||
if (!tenant) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setSelectedBranch(branch);
|
||||
|
||||
try {
|
||||
const branchServices = await getBranchServices(tenant.code, branch.id);
|
||||
setServices(branchServices);
|
||||
setStep("service");
|
||||
} catch {
|
||||
setError("Could not load services for this branch.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSelectService(service: Service) {
|
||||
if (!selectedBranch) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await createTicket({
|
||||
branchId: selectedBranch.id,
|
||||
serviceId: service.id,
|
||||
deviceToken: getDeviceToken(),
|
||||
});
|
||||
setTicket(response.ticket);
|
||||
setStep("ticket");
|
||||
} catch {
|
||||
setError(
|
||||
"Could not get a ticket number. Make sure this branch has services assigned."
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function resetFlow() {
|
||||
setStep(tenant ? "branch" : "tenant");
|
||||
setSelectedBranch(null);
|
||||
setServices([]);
|
||||
setTicket(null);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function startOver() {
|
||||
setStep("tenant");
|
||||
setTenant(null);
|
||||
setBranches([]);
|
||||
setSelectedBranch(null);
|
||||
setServices([]);
|
||||
setTicket(null);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-full w-full max-w-xl flex-col gap-8 px-6 py-12">
|
||||
<header className="space-y-2">
|
||||
<p className="text-sm tracking-wide text-zinc-500 uppercase">
|
||||
Queue Management
|
||||
</p>
|
||||
<h1 className="text-3xl font-semibold tracking-tight text-zinc-900">
|
||||
{tenant?.name ?? "Get a ticket"}
|
||||
</h1>
|
||||
<p className="text-base text-zinc-600">
|
||||
{tenant?.welcomeMessage ??
|
||||
"Enter your company code, pick a branch and service, then take a number."}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<p className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{step === "tenant" ? (
|
||||
<form onSubmit={handleTenantSubmit} className="space-y-4">
|
||||
<label className="block space-y-2">
|
||||
<span className="text-sm font-medium text-zinc-700">
|
||||
Company code
|
||||
</span>
|
||||
<input
|
||||
value={tenantCode}
|
||||
onChange={(event) => setTenantCode(event.target.value)}
|
||||
className="w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-zinc-900 outline-none focus:border-zinc-900"
|
||||
placeholder="e.g. DFLT"
|
||||
autoComplete="off"
|
||||
disabled={loading}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-md bg-zinc-900 px-4 py-3 text-sm font-medium text-white disabled:opacity-60"
|
||||
>
|
||||
{loading ? "Loading…" : "Continue"}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
|
||||
{step === "branch" ? (
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-lg font-medium text-zinc-900">Choose a branch</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={startOver}
|
||||
className="text-sm text-zinc-500 underline-offset-2 hover:underline"
|
||||
>
|
||||
Change company
|
||||
</button>
|
||||
</div>
|
||||
{branches.length === 0 ? (
|
||||
<p className="text-sm text-zinc-600">No branches available.</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{branches.map((branch) => (
|
||||
<li key={branch.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => handleSelectBranch(branch)}
|
||||
className="flex w-full items-center justify-between rounded-md border border-zinc-200 bg-white px-4 py-3 text-left text-zinc-900 transition hover:border-zinc-400 disabled:opacity-60"
|
||||
>
|
||||
<span>{branch.name}</span>
|
||||
<span className="text-zinc-400">→</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{step === "service" && selectedBranch ? (
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-lg font-medium text-zinc-900">
|
||||
Service at {selectedBranch.name}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setStep("branch");
|
||||
setSelectedBranch(null);
|
||||
setServices([]);
|
||||
setError(null);
|
||||
}}
|
||||
className="text-sm text-zinc-500 underline-offset-2 hover:underline"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
{services.length === 0 ? (
|
||||
<p className="text-sm text-zinc-600">
|
||||
No services are assigned to this branch yet. Link services via a
|
||||
branch group in the admin app, then try again.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{services.map((service) => (
|
||||
<li key={service.id}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => handleSelectService(service)}
|
||||
className="flex w-full items-center justify-between rounded-md border border-zinc-200 bg-white px-4 py-3 text-left text-zinc-900 transition hover:border-zinc-400 disabled:opacity-60"
|
||||
>
|
||||
<span>{service.name}</span>
|
||||
<span className="text-sm text-zinc-500">
|
||||
{loading ? "…" : "Get number"}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{step === "ticket" && ticket ? (
|
||||
<section className="space-y-6 rounded-md border border-zinc-200 bg-white px-6 py-8 text-center">
|
||||
<p className="text-sm tracking-wide text-zinc-500 uppercase">
|
||||
Your ticket number
|
||||
</p>
|
||||
<p className="text-6xl font-semibold tracking-tight text-zinc-900">
|
||||
{ticket.number}
|
||||
</p>
|
||||
<div className="space-y-1 text-sm text-zinc-600">
|
||||
<p>{ticket.service.name}</p>
|
||||
<p>{ticket.branch.name}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetFlow}
|
||||
className="w-full rounded-md bg-zinc-900 px-4 py-3 text-sm font-medium text-white"
|
||||
>
|
||||
Get another ticket
|
||||
</button>
|
||||
</section>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,82 @@
|
||||
import { SERVER_URL } from "./constants";
|
||||
|
||||
export type Tenant = {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
welcomeMessage: string;
|
||||
font: string | null;
|
||||
logo?: { id: number; base64Logo: string | null } | null;
|
||||
};
|
||||
|
||||
export type Branch = {
|
||||
id: number;
|
||||
name: string;
|
||||
tellerStations: { id: number; name: string }[];
|
||||
};
|
||||
|
||||
export type Service = {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type Ticket = {
|
||||
id: number;
|
||||
number: string;
|
||||
createdAt: string;
|
||||
service: Service;
|
||||
branch: Branch;
|
||||
station: { id: number; name: string } | null;
|
||||
};
|
||||
|
||||
export type TicketResponse = {
|
||||
ticket: Ticket;
|
||||
stations: { id: number; name: string }[];
|
||||
};
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(`${SERVER_URL}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Request failed (${response.status}) for ${path}`);
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export function getTenant(code: string) {
|
||||
return request<Tenant>(`/api/v1/tenants/${encodeURIComponent(code)}`);
|
||||
}
|
||||
|
||||
export function getBranches(tenantCode: string) {
|
||||
return request<Branch[]>(
|
||||
`/api/v1/branches/${encodeURIComponent(tenantCode)}`
|
||||
);
|
||||
}
|
||||
|
||||
export function getBranchServices(tenantCode: string, branchId: number) {
|
||||
return request<Service[]>(
|
||||
`/api/v1/branches/${encodeURIComponent(tenantCode)}/${branchId}/services`
|
||||
);
|
||||
}
|
||||
|
||||
export function createTicket(input: {
|
||||
branchId: number;
|
||||
serviceId: number;
|
||||
deviceToken: string;
|
||||
}) {
|
||||
return request<TicketResponse>("/api/v1/tickets", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function getTicketById(ticketId: number | string) {
|
||||
return request<Ticket>(`/api/v1/tickets/${ticketId}`);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export const SERVER_URL =
|
||||
process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8080";
|
||||
|
||||
export const DEVICE_TOKEN_KEY = "qms_device_token";
|
||||
@@ -0,0 +1,20 @@
|
||||
import { DEVICE_TOKEN_KEY } from "./constants";
|
||||
|
||||
export function getDeviceToken(): string {
|
||||
if (typeof window === "undefined") {
|
||||
return "";
|
||||
}
|
||||
|
||||
const existing = window.localStorage.getItem(DEVICE_TOKEN_KEY);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof crypto !== "undefined" && "randomUUID" in crypto
|
||||
? crypto.randomUUID()
|
||||
: `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
window.localStorage.setItem(DEVICE_TOKEN_KEY, token);
|
||||
return token;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "customer-app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "16.2.10",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.10",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
Generated
+4102
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
ignoredBuiltDependencies:
|
||||
- sharp
|
||||
- unrs-resolver
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -1,20 +1,61 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import StationIntroPage from './pages/StationIntroPage/StationIntroPage.jsx';
|
||||
import ShowQueuesForTellerPage from './pages/ShowQueuesForTellerPage/ShowQueuesForTellerPage';
|
||||
import Header from './components/Header/Header.jsx';
|
||||
import CurrentTicketPage from './pages/CurrentTicketPage/CurrentTicketPage.jsx';
|
||||
import LoginPage from './pages/LoginPage/LoginPage.jsx';
|
||||
import AuthGuard from './components/AuthGuard/AuthGuard.jsx';
|
||||
import { UserContext } from './context/UserContext.jsx';
|
||||
import { clearSession, getToken, getUserData } from './utils/session.js';
|
||||
import { SERVER_URL } from './constants.js';
|
||||
import { fetchData } from './fetching/Fetch.js';
|
||||
|
||||
export default function App() {
|
||||
const [user, setUser] = useState(() => getUserData());
|
||||
|
||||
useEffect(() => {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetchData(`${SERVER_URL}/api/v1/auth`, 'GET').then(({ success }) => {
|
||||
if (success) {
|
||||
setUser(getUserData());
|
||||
} else {
|
||||
clearSession();
|
||||
setUser(null);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<UserContext.Provider value={{ user, setUser }}>
|
||||
<Header />
|
||||
<Routes>
|
||||
<Route exact path='/' element={<StationIntroPage />} />
|
||||
<Route exact path="/teller-queue/:stationId" element={<ShowQueuesForTellerPage />} />
|
||||
<Route path="/display/:stationId" element={<CurrentTicketPage/>} />
|
||||
<Route exact path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
exact
|
||||
path="/"
|
||||
element={
|
||||
<AuthGuard>
|
||||
<StationIntroPage />
|
||||
</AuthGuard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path="/teller-queue/:stationId"
|
||||
element={
|
||||
<AuthGuard>
|
||||
<ShowQueuesForTellerPage />
|
||||
</AuthGuard>
|
||||
}
|
||||
/>
|
||||
{/* Public display board for waiting area screens */}
|
||||
<Route path="/display/:stationId" element={<CurrentTicketPage />} />
|
||||
</Routes>
|
||||
</>
|
||||
</UserContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useContext, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { getUserData } from '../../utils/session.js';
|
||||
import { ROLES } from '../../constants.js';
|
||||
|
||||
const TELLER_ROLES = [
|
||||
ROLES.ROLE_USER,
|
||||
ROLES.ROLE_SUPER_ADMIN,
|
||||
ROLES.ROLE_BRANCH_ADMIN,
|
||||
];
|
||||
|
||||
export default function AuthGuard({ children }) {
|
||||
const navigate = useNavigate();
|
||||
const { user: contextUser } = useContext(UserContext);
|
||||
const [allowed, setAllowed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const user = contextUser ?? getUserData();
|
||||
const roles = Array.isArray(user?.roles) ? user.roles : [];
|
||||
const hasAccess = roles.some((role) => TELLER_ROLES.includes(role));
|
||||
|
||||
if (!user || !hasAccess) {
|
||||
setAllowed(false);
|
||||
navigate('/login', { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
setAllowed(true);
|
||||
}, [contextUser, navigate]);
|
||||
|
||||
if (!allowed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -15,4 +15,25 @@ header.main-header {
|
||||
margin-top: 7px;
|
||||
margin-right: auto;
|
||||
margin-left: 2%;
|
||||
}
|
||||
|
||||
.header-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-right: 2%;
|
||||
}
|
||||
|
||||
.header-email {
|
||||
font-size: 14px;
|
||||
color: #334257;
|
||||
}
|
||||
|
||||
.header-logout-btn {
|
||||
border: 1px solid #334257;
|
||||
background: white;
|
||||
color: #334257;
|
||||
border-radius: 4px;
|
||||
padding: 6px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -1,13 +1,32 @@
|
||||
import './Header.css';
|
||||
import { useContext } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { clearSession } from '../../utils/session.js';
|
||||
|
||||
export default function Header() {
|
||||
const navigate = useNavigate();
|
||||
const { user, setUser } = useContext(UserContext);
|
||||
|
||||
function handleLogout() {
|
||||
clearSession();
|
||||
setUser(null);
|
||||
navigate('/login', { replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="main-header">
|
||||
<h2 className="header-logo" onClick={() => navigate(`/`)}>BBQMS</h2>
|
||||
<h2 className="header-logo" onClick={() => navigate(user ? '/' : '/login')}>
|
||||
BBQMS Teller
|
||||
</h2>
|
||||
{user ? (
|
||||
<div className="header-user">
|
||||
<span className="header-email">{user.email}</span>
|
||||
<button type="button" className="header-logout-btn" onClick={handleLogout}>
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,7 @@
|
||||
export const SERVER_URL = 'http://localhost:8080';
|
||||
|
||||
export const ROLES = {
|
||||
ROLE_USER: 'ROLE_USER',
|
||||
ROLE_SUPER_ADMIN: 'ROLE_SUPER_ADMIN',
|
||||
ROLE_BRANCH_ADMIN: 'ROLE_BRANCH_ADMIN',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const UserContext = createContext({
|
||||
user: null,
|
||||
setUser: () => {},
|
||||
});
|
||||
@@ -1,12 +1,14 @@
|
||||
/*
|
||||
Koristiti ovu funkciju za fetchanje u buducnosti kad god je to moguce.
|
||||
*/
|
||||
import { getToken, setToken } from '../utils/session.js';
|
||||
|
||||
export async function fetchData(url, method, body) {
|
||||
const headers = new Headers();
|
||||
|
||||
const token = localStorage.getItem('token');
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
headers.append('Authorization', `Bearer ${ token }`);
|
||||
headers.append('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
|
||||
headers.append('Content-Type', 'application/json');
|
||||
@@ -14,7 +16,7 @@ export async function fetchData(url, method, body) {
|
||||
const res = await fetch(url, {
|
||||
method: method || 'GET',
|
||||
headers: headers,
|
||||
body: body ? JSON.stringify(body) : null
|
||||
body: body ? JSON.stringify(body) : null,
|
||||
});
|
||||
|
||||
if (!res) {
|
||||
@@ -24,12 +26,11 @@ export async function fetchData(url, method, body) {
|
||||
const data = res.ok && res.body ? await res.json() : null;
|
||||
|
||||
if (res.ok) {
|
||||
//na svaki ispravan rezultat treba da dobijemo novi token da refreshamo stari
|
||||
const newToken = res.headers.get('Auth-Token');
|
||||
if (newToken) {
|
||||
localStorage.setItem('token', newToken);
|
||||
setToken(newToken);
|
||||
}
|
||||
}
|
||||
|
||||
return { data: data, success: res.ok };
|
||||
}
|
||||
return { data, success: res.ok };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#teller-login-form {
|
||||
width: 420px;
|
||||
max-width: 100%;
|
||||
margin: 80px auto 40px;
|
||||
background-color: #334257;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
#teller-login-form h1 {
|
||||
margin: 0;
|
||||
padding: 20px 0;
|
||||
text-align: center;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#teller-login-form form {
|
||||
padding: 20px;
|
||||
background-color: white;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
#teller-login-form .form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
#teller-login-form label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-size: 14px;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
#teller-login-form input {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 1px solid #d0d0d0;
|
||||
border-radius: 5px;
|
||||
font-size: 16px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#teller-login-form button {
|
||||
width: 100%;
|
||||
margin-top: 8px;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background-color: #548ca8;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#teller-login-form button:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
#teller-login-form .error {
|
||||
margin: 0 0 12px;
|
||||
color: #b00020;
|
||||
font-size: 14px;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { useContext, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ROLES, SERVER_URL } from '../../constants.js';
|
||||
import { fetchData } from '../../fetching/Fetch.js';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
import { clearSession, getToken, setSession } from '../../utils/session.js';
|
||||
import './LoginPage.css';
|
||||
|
||||
const TELLER_ROLES = [
|
||||
ROLES.ROLE_USER,
|
||||
ROLES.ROLE_SUPER_ADMIN,
|
||||
ROLES.ROLE_BRANCH_ADMIN,
|
||||
];
|
||||
|
||||
function canAccessTellerApp(userData) {
|
||||
const roles = Array.isArray(userData?.roles) ? userData.roles : [];
|
||||
return roles.some((role) => TELLER_ROLES.includes(role));
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { user, setUser } = useContext(UserContext);
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (user && getToken()) {
|
||||
navigate('/', { replace: true });
|
||||
}
|
||||
}, [user, navigate]);
|
||||
|
||||
async function handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
setError('Email is required.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!password.trim()) {
|
||||
setError('Password is required.');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const { data, success } = await fetchData(`${SERVER_URL}/api/v1/auth/login`, 'POST', {
|
||||
email: email.trim(),
|
||||
password: password.trim(),
|
||||
});
|
||||
|
||||
if (!success || !data) {
|
||||
setError('Your credentials are incorrect.');
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = data.userData ?? data;
|
||||
const token = data.token;
|
||||
|
||||
if (!canAccessTellerApp(userData)) {
|
||||
clearSession();
|
||||
setUser(null);
|
||||
setError('This account cannot access the teller app.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
setError('Two-factor login is not supported in the teller app yet. Disable 2FA for this account or use an account without 2FA.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!userData?.tenantCode) {
|
||||
setError('Login succeeded but tenant information is missing.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSession({ userData, token });
|
||||
setUser(userData);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setError('An error occurred. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="teller-login-form">
|
||||
<h1>Teller Login</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="email">Email</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
autoComplete="username"
|
||||
onChange={(event) => {
|
||||
setEmail(event.target.value);
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="password">Password</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
autoComplete="current-password"
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="error">{error}</p> : null}
|
||||
<button type="submit" disabled={loading}>
|
||||
{loading ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +1,148 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Dropdown, Button } from 'react-bootstrap';
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
import { Dropdown } from 'react-bootstrap';
|
||||
import { fetchData } from '../../fetching/Fetch.js';
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import { SERVER_URL } from '../../constants.js';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { UserContext } from '../../context/UserContext.jsx';
|
||||
|
||||
const StationIntroPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const { user } = useContext(UserContext);
|
||||
|
||||
const [branches, setBranches] = useState([]);
|
||||
const [selectedBranch, setSelectedBranch] = useState(null);
|
||||
const [stations, setStations] = useState([]);
|
||||
const [selectedStation, setSelectedStation] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const [loadingBranches, setLoadingBranches] = useState(false);
|
||||
const [loadingStations, setLoadingStations] = useState(false);
|
||||
|
||||
const url = `${ SERVER_URL }/api/v1/`;
|
||||
const tenantCode = user?.tenantCode;
|
||||
const url = `${SERVER_URL}/api/v1/`;
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(`${ url }branches/DFLT`, 'GET')
|
||||
.then(response => response.data)
|
||||
.then(setBranches)
|
||||
.catch(console.error)
|
||||
}, []);
|
||||
if (!tenantCode) {
|
||||
setBranches([]);
|
||||
setError('Missing tenant on your account.');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingBranches(true);
|
||||
setError('');
|
||||
fetchData(`${url}branches/${encodeURIComponent(tenantCode)}`, 'GET')
|
||||
.then(({ data, success }) => {
|
||||
if (!success) {
|
||||
setBranches([]);
|
||||
setError('Could not load branches for your tenant.');
|
||||
return;
|
||||
}
|
||||
setBranches(Array.isArray(data) ? data : []);
|
||||
if (!data?.length) {
|
||||
setError(`No branches found for tenant ${tenantCode}.`);
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
setError('Could not load branches.');
|
||||
})
|
||||
.finally(() => setLoadingBranches(false));
|
||||
}, [tenantCode]);
|
||||
|
||||
function handleBranchSelect(branch) {
|
||||
setSelectedBranch(branch)
|
||||
fetchData(`${ url }stations/DFLT/${ branch.id }`, 'GET')
|
||||
.then(response => response.data)
|
||||
.then(setStations)
|
||||
.catch(console.error)
|
||||
setSelectedBranch(branch);
|
||||
setSelectedStation(null);
|
||||
setStations([]);
|
||||
setLoadingStations(true);
|
||||
setError('');
|
||||
|
||||
fetchData(`${url}stations/${encodeURIComponent(tenantCode)}/${branch.id}`, 'GET')
|
||||
.then(({ data, success }) => {
|
||||
if (!success) {
|
||||
setStations([]);
|
||||
setError('Could not load stations for this branch.');
|
||||
return;
|
||||
}
|
||||
setStations(Array.isArray(data) ? data : []);
|
||||
if (!data?.length) {
|
||||
setError('No stations found for this branch.');
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
setError('Could not load stations.');
|
||||
})
|
||||
.finally(() => setLoadingStations(false));
|
||||
}
|
||||
|
||||
function handleStationSelect(station) {
|
||||
navigate(`/teller-queue/${ station.id }`)
|
||||
setSelectedStation(station);
|
||||
navigate(`/teller-queue/${station.id}`);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-center mt-5">
|
||||
<div className="border p-3" style={{ maxWidth: '500px', margin: '0 auto' }}>
|
||||
<h1 className="mb-4">Select Branch and Station</h1>
|
||||
<h1 className="mb-2">Select Branch and Station</h1>
|
||||
{tenantCode ? (
|
||||
<p className="text-muted mb-4">Tenant: {tenantCode}</p>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="text-danger">{error}</p> : null}
|
||||
|
||||
<Dropdown>
|
||||
<Dropdown.Toggle variant="primary" id="dropdown-branch" style={{ width: '100%' }}>
|
||||
{selectedBranch ? selectedBranch.name : 'Select Branch'}
|
||||
<Dropdown.Toggle
|
||||
variant="primary"
|
||||
id="dropdown-branch"
|
||||
style={{ width: '100%' }}
|
||||
disabled={loadingBranches || branches.length === 0}
|
||||
>
|
||||
{loadingBranches
|
||||
? 'Loading branches…'
|
||||
: selectedBranch
|
||||
? selectedBranch.name
|
||||
: 'Select Branch'}
|
||||
</Dropdown.Toggle>
|
||||
<Dropdown.Menu style={{ width: '100%' }}>
|
||||
{branches.map(branch => (
|
||||
<Dropdown.Item key={branch.id} onClick={() => handleBranchSelect(branch)}>
|
||||
{branches.map((branch) => (
|
||||
<Dropdown.Item
|
||||
key={branch.id}
|
||||
onClick={() => handleBranchSelect(branch)}
|
||||
>
|
||||
{branch.name}
|
||||
</Dropdown.Item>
|
||||
))}
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
|
||||
{selectedBranch && (
|
||||
{selectedBranch ? (
|
||||
<div className="mt-3">
|
||||
<Dropdown>
|
||||
<Dropdown.Toggle variant="primary" id="dropdown-station" style={{ width: '100%' }}>
|
||||
{selectedStation ? selectedStation.name : 'Select Station'}
|
||||
<Dropdown.Toggle
|
||||
variant="primary"
|
||||
id="dropdown-station"
|
||||
style={{ width: '100%' }}
|
||||
disabled={loadingStations || stations.length === 0}
|
||||
>
|
||||
{loadingStations
|
||||
? 'Loading stations…'
|
||||
: selectedStation
|
||||
? selectedStation.name
|
||||
: 'Select Station'}
|
||||
</Dropdown.Toggle>
|
||||
<Dropdown.Menu style={{ width: '100%' }}>
|
||||
{stations.map(station => (
|
||||
<Dropdown.Item key={station.id} onClick={() => handleStationSelect(station)}>
|
||||
{stations.map((station) => (
|
||||
<Dropdown.Item
|
||||
key={station.id}
|
||||
onClick={() => handleStationSelect(station)}
|
||||
>
|
||||
{station.name}
|
||||
</Dropdown.Item>
|
||||
))}
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
const TOKEN_KEY = 'teller_token';
|
||||
const USER_DATA_KEY = 'teller_userData';
|
||||
|
||||
/** Matches backend jwt.token-validity-time (PT30M). */
|
||||
const SESSION_MAX_AGE_SECONDS = 30 * 60;
|
||||
|
||||
function getCookie(name) {
|
||||
const prefix = `${encodeURIComponent(name)}=`;
|
||||
const parts = document.cookie ? document.cookie.split('; ') : [];
|
||||
|
||||
for (const part of parts) {
|
||||
if (part.startsWith(prefix)) {
|
||||
return decodeURIComponent(part.slice(prefix.length));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function setCookie(name, value, maxAgeSeconds = SESSION_MAX_AGE_SECONDS) {
|
||||
const secure = window.location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = [
|
||||
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
|
||||
'Path=/',
|
||||
`Max-Age=${maxAgeSeconds}`,
|
||||
'SameSite=Lax',
|
||||
secure,
|
||||
].join('; ');
|
||||
}
|
||||
|
||||
function removeCookie(name) {
|
||||
document.cookie = `${encodeURIComponent(name)}=; Path=/; Max-Age=0; SameSite=Lax`;
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return getCookie(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setToken(token) {
|
||||
if (token == null || token === '') {
|
||||
removeCookie(TOKEN_KEY);
|
||||
return;
|
||||
}
|
||||
setCookie(TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
export function getUserData() {
|
||||
const raw = getCookie(USER_DATA_KEY) ?? sessionStorage.getItem(USER_DATA_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
removeCookie(USER_DATA_KEY);
|
||||
sessionStorage.removeItem(USER_DATA_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setUserData(userData) {
|
||||
if (userData == null) {
|
||||
removeCookie(USER_DATA_KEY);
|
||||
sessionStorage.removeItem(USER_DATA_KEY);
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(userData);
|
||||
setCookie(USER_DATA_KEY, serialized);
|
||||
sessionStorage.setItem(USER_DATA_KEY, serialized);
|
||||
}
|
||||
|
||||
export function setSession({ token, userData } = {}) {
|
||||
if (token !== undefined) {
|
||||
setToken(token);
|
||||
}
|
||||
if (userData !== undefined) {
|
||||
setUserData(userData);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
removeCookie(TOKEN_KEY);
|
||||
removeCookie(USER_DATA_KEY);
|
||||
sessionStorage.removeItem(USER_DATA_KEY);
|
||||
}
|
||||
Reference in New Issue
Block a user