Optimize sign up ux; Add confirmation for promotion

pull/1/head
Florian Hartwich 2017-06-11 13:18:03 +02:00
parent 720df45cfd
commit a354b1ddc8
15 changed files with 153 additions and 140 deletions

View File

@ -102,7 +102,7 @@ let create = (userParam) => {
if (user) { if (user) {
// username already exists // username already exists
deferred.reject('Username "' + userParam.username + '" is already taken'); deferred.reject(new Error("Username already exists"));
} else { } else {
createUser(); createUser();
} }

View File

@ -9,6 +9,10 @@ const codes = require('./http-codes');
const routerHandling = require('../middleware/router-handling'); const routerHandling = require('../middleware/router-handling');
const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
const checkSql = require('../middleware/permission-check').checkSql;
const checkHl = require('../middleware/permission-check').checkHl;
// Mongoose Model using mongoDB // Mongoose Model using mongoDB
const UserModel = require('../models/user'); const UserModel = require('../models/user');
const AwardingModel = require('../models/awarding'); const AwardingModel = require('../models/awarding');
@ -31,7 +35,7 @@ const request = express.Router();
// routes ********************** // routes **********************
request.route('/award') request.route('/award')
.post((req, res, next) => { .post(apiAuthenticationMiddleware, checkSql, (req, res, next) => {
const award = new AwardingModel(req.body); const award = new AwardingModel(req.body);
award.confirmed = 0; award.confirmed = 0;
award.proposer = req.user._id; award.proposer = req.user._id;
@ -54,18 +58,36 @@ request.route('/award')
request.route('/promotion') request.route('/promotion')
.get((req, res, next) => { .get(apiAuthenticationMiddleware, checkSql, (req, res, next) => {
const squadFilter = req.query.squadId; const squadFilter = req.query.squadId;
const fractFilter = req.query.fractFilter;
const progressFilter = req.query.inProgress;
let filter;
if (squadFilter) {
filter = {squadId: squadFilter};
}
let userIds = []; let userIds = [];
UserModel.find({squadId: squadFilter}, (err, items) => { UserModel.find(filter).populate('squadId').exec((err, items) => {
if (err) { if (err) {
err.status = codes.servererror; err.status = codes.servererror;
return next(err); return next(err);
} }
for (let item of items) { for (let item of items) {
if (!fractFilter || (fractFilter && item.squadId && item.squadId.fraction === fractFilter)) {
userIds.push(item._id); userIds.push(item._id);
} }
PromotionModel.find({userId: {"$in": userIds}}, {}, {sort: {timestamp: 'desc'}}).populate('userId').populate('proposer', resultSet).exec((err, items) => { }
let promotionFilter = {
userId: {"$in": userIds}
};
if (progressFilter) {
promotionFilter.confirmed = 0;
}
PromotionModel.find(promotionFilter, {}, {sort: {timestamp: 'desc'}})
.populate('userId').populate('proposer', resultSet).exec((err, items) => {
if (err) { if (err) {
err.status = codes.servererror; err.status = codes.servererror;
return next(err); return next(err);
@ -83,7 +105,7 @@ request.route('/promotion')
}) })
.post((req, res, next) => { .post(apiAuthenticationMiddleware, checkSql, (req, res, next) => {
const promotion = new PromotionModel(req.body); const promotion = new PromotionModel(req.body);
promotion.confirmed = 0; promotion.confirmed = 0;
promotion.proposer = req.user._id; promotion.proposer = req.user._id;
@ -104,6 +126,54 @@ request.route('/promotion')
routerHandling.httpMethodNotAllowed routerHandling.httpMethodNotAllowed
); );
request.route('/promotion/:id')
.patch(apiAuthenticationMiddleware, checkHl, (req, res, next) => {
if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
// little bit different as in PUT. :id does not need to be in data, but if the _id and url id must match
const err = new Error('id of PATCH resource and send JSON body are not equal ' + req.params.id + " " + req.body._id);
err.status = codes.notfound;
next(err);
return; // prevent node to process this function further after next() has finished.
}
req.body.updatedAt = new Date();
req.body.$inc = {__v: 1};
// PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no need to reset attributes that are missing.
PromotionModel.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("item not found");
err.status = codes.notfound;
}
else {
if (item.confirmed === 1) {
let updateUser = {
_id: item.userId,
rankLvl: item.newRankLvl
};
UserModel.findByIdAndUpdate(updateUser._id, updateUser, {new: true}, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("user not found");
err.status = codes.notfound;
}
});
}
res.locals.items = item;
}
next(err);
})
})
.all(
routerHandling.httpMethodNotAllowed
);
// this middleware function can be used, if you like or remove it // this middleware function can be used, if you like or remove it
// it looks for object(s) in res.locals.items and if they exist, they are send to the client as json // it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
request.use(routerHandling.emptyResponse); request.use(routerHandling.emptyResponse);

View File

@ -73,7 +73,7 @@ app.use(urls.users, userRouter);
app.use(urls.squads, squadRouter); app.use(urls.squads, squadRouter);
app.use(urls.ranks, rankRouter); app.use(urls.ranks, rankRouter);
app.use(urls.decorations, decorationRouter); app.use(urls.decorations, decorationRouter);
app.use(urls.request, apiAuthenticationMiddleware, checkSql, requestRouter); app.use(urls.request, requestRouter);
app.use(urls.awards, awardingRouter); app.use(urls.awards, awardingRouter);
app.use(urls.command, apiAuthenticationMiddleware, checkAdmin, commandRouter); app.use(urls.command, apiAuthenticationMiddleware, checkAdmin, commandRouter);
app.use(urls.account, apiAuthenticationMiddleware, checkAdmin, accountRouter); app.use(urls.account, apiAuthenticationMiddleware, checkAdmin, accountRouter);

View File

@ -126,7 +126,7 @@ let addDecorationsAndSave = (userId, loadedImage, res, next) => {
let ribbonPx = 598; let ribbonPx = 598;
let ribbonPy = 95; let ribbonPy = 95;
AwardingModel.find({'userId': userId}, ['decorationId', 'date'], AwardingModel.find({'userId': userId, 'confirmed': 1}, ['decorationId', 'date'],
{sort: {date: 'asc'}}).populate('decorationId', ['isMedal']) {sort: {date: 'asc'}}).populate('decorationId', ['isMedal'])
.exec((err, awardings) => { .exec((err, awardings) => {
if (err) { if (err) {

View File

@ -3,9 +3,11 @@
<div class="row"> <div class="row">
<h2 style="text-align: center;" class="form-signin-heading">Registrieren</h2> <h2 style="text-align: center;" class="form-signin-heading">Registrieren</h2>
<p>Dieses Formular nur ausfüllen wenn du einer <b>HL</b> angehörst oder <b>SQL</b> bist. Dabei den Nutzernamen aus dem OPT Forum verwenden! <p>Dieses Formular nur ausfüllen wenn du einer <b>HL</b> angehörst oder <b>SQL</b> bist. Dabei den Nutzernamen aus
Im Forum eine Nachricht an <a href="https://opt-dev.de/dashboard/index.php?conversation-add/&userID=9" target="_blank">HardiReady</a> dem OPT Forum verwenden!
senden, in welcher der 'geheime Text' drin steht, den du bei der Registrierung nutzt.<br> Im Forum eine Nachricht an <a href="https://opt-dev.de/dashboard/index.php?conversation-add/&userID=9"
target="_blank">HardiReady</a>
senden, in welcher der 'geheime Text' steht, den du bei der Registrierung nutzt.<br>
Dabei kann es sich um irgend eine willkürliche Zeichenfolge oder einen Satz handeln - dient nur dem Abgleich. Dabei kann es sich um irgend eine willkürliche Zeichenfolge oder einen Satz handeln - dient nur dem Abgleich.
Anschließend wird dein Account aktiviert und du wirst darüber per PN informiert.</p> Anschließend wird dein Account aktiviert und du wirst darüber per PN informiert.</p>
@ -25,9 +27,16 @@
<span *ngIf="!loading">Registrieren</span> <span *ngIf="!loading">Registrieren</span>
<span *ngIf="loading" class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> <span *ngIf="loading" class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>
</button> </button>
<h3 class="text-center">
<span *ngIf="showSuccessLabel"
class="label label-success label-small"
style="margin-left: inherit">
Account erfolgreich erstellt
</span>
</h3>
<span *ngIf="showErrorLabel" <span *ngIf="showErrorLabel"
class="center-block label label-danger" style="font-size: medium; padding: 2px; margin-top: 2px"> class="center-block label label-danger" style="font-size: medium; padding: 2px; margin-top: 2px">
Login fehlgeschlagen {{error}}
</span> </span>
</div> </div>

View File

@ -13,6 +13,10 @@ export class SignupComponent implements OnInit {
showErrorLabel = false; showErrorLabel = false;
showSuccessLabel = false;
error: string;
loading = false; loading = false;
returnUrl: string; returnUrl: string;
@ -35,10 +39,11 @@ export class SignupComponent implements OnInit {
this.loginService.signUp(username, password, secret) this.loginService.signUp(username, password, secret)
.subscribe( .subscribe(
data => { data => {
console.log(data) this.loading = false;
//this.router.navigate([this.returnUrl]); this.showSuccessLabel = true;
}, },
error => { error => {
this.error = error;
this.showErrorLabel = true; this.showErrorLabel = true;
setTimeout(() => { setTimeout(() => {
this.showErrorLabel = false; this.showErrorLabel = false;

View File

@ -41,6 +41,7 @@ export interface Award {
} }
export interface Promotion { export interface Promotion {
_id?: string;
userId?: string userId?: string
oldRankLvl: number, oldRankLvl: number,
newRankLvl: number newRankLvl: number

View File

@ -1,6 +1,12 @@
<form #form="ngForm" class="overview"> <form #form="ngForm" class="overview">
<h3>Offene Anträge - Auszeichnungen</h3> <h3>Offene Anträge - Auszeichnungen</h3>
<span *ngIf="showSuccessLabel"
class="label label-success label-small"
style="margin-left: inherit">
Erfolgreich gespeichert
</span>
<div class="table-container"> <div class="table-container">
<table class="table table-hover"> <table class="table table-hover">
<thead> <thead>

View File

@ -9,8 +9,11 @@ import {AwardingService} from "../../services/awarding-service/awarding.service"
styleUrls: ['./confirm-award.component.css'], styleUrls: ['./confirm-award.component.css'],
}) })
export class ConfirmAwardComponent { export class ConfirmAwardComponent {
awards: Award[]; awards: Award[];
showSuccessLabel = false;
constructor(private router: Router, constructor(private router: Router,
private route: ActivatedRoute, private route: ActivatedRoute,
private awardingService: AwardingService) { private awardingService: AwardingService) {
@ -34,6 +37,10 @@ export class ConfirmAwardComponent {
let currentUser = JSON.parse(localStorage.getItem('currentUser')); let currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.awardingService.getUnconfirmedAwards(currentUser.squad.fraction).subscribe(awards => { this.awardingService.getUnconfirmedAwards(currentUser.squad.fraction).subscribe(awards => {
this.awards = awards; this.awards = awards;
this.showSuccessLabel = true;
setTimeout(() => {
this.showSuccessLabel = false;
}, 2000);
}); });
}); });
} }

View File

@ -2,7 +2,7 @@
padding: 5px; padding: 5px;
} }
.trash { .action {
cursor: pointer; cursor: pointer;
} }

View File

@ -1,60 +1,5 @@
<form #form="ngForm" class="overview"> <form #form="ngForm" class="overview">
<h3>Beförderung beantragen</h3> <h3>Offene Anträge - Beförderung</h3>
<div class="form-group">
<label for="user">Teilnehmer</label>
<select class="form-control"
name="user"
id="user"
[(ngModel)]="user"
[compareWith]="equals"
required
(change)="toggleUser()">
<option *ngFor="let user of users" [ngValue]="user">
{{user.username}}
</option>
</select>
</div>
<div *ngIf="showForm">
<div class="form-group">
<label for="user">Aktueller Rang</label>
<input class="form-control"
[(ngModel)]="user.rank.name"
[ngModelOptions]="{standalone: true}"
readonly>
</div>
<div class="form-group">
<label for="decoration">Neuer Rang</label>
<select class="form-control"
name="decoration"
id="decoration"
#decorationField
[(ngModel)]="newLevel"
required>
<option *ngFor="let rank of ranks" [ngValue]="rank.level">
{{rank.name}}
</option>
</select>
</div>
</div>
<button id="cancel"
(click)="cancel()"
class="btn btn-default">
Abbrechen
</button>
<button id="save"
*ngIf="showForm"
(click)="addPromotion()"
class="btn btn-default"
[disabled]="newLevel === user.rank.level">
Bestätigen
</button>
<span *ngIf="showSuccessLabel" <span *ngIf="showSuccessLabel"
class="label label-success label-small" class="label label-success label-small"
@ -62,7 +7,6 @@
Erfolgreich gespeichert Erfolgreich gespeichert
</span> </span>
<div class="table-container"> <div class="table-container">
<label>Beförderungsanträge</label> <label>Beförderungsanträge</label>
<table class="table table-hover"> <table class="table table-hover">
@ -74,9 +18,10 @@
<th class="col-sm-1 ">Antragsteller</th> <th class="col-sm-1 ">Antragsteller</th>
<th class="col-sm-1 text-center">Datum</th> <th class="col-sm-1 text-center">Datum</th>
<th class="col-sm-1 text-center">Status</th> <th class="col-sm-1 text-center">Status</th>
<th class="col-sm-1 text-center">Aktion</th>
</tr> </tr>
</thead> </thead>
<tbody *ngFor="let promotion of uncheckedPromotions"> <tbody *ngFor="let promotion of promotions">
<tr> <tr>
<td> <td>
{{promotion.userId.username}} {{promotion.userId.username}}
@ -96,6 +41,10 @@
<td class="text-center"> <td class="text-center">
{{promotion.confirmed === 0? 'In Bearbeitung' : (promotion.confirmed === 1? 'Genehmigt' : 'Abgelehnt')}} {{promotion.confirmed === 0? 'In Bearbeitung' : (promotion.confirmed === 1? 'Genehmigt' : 'Abgelehnt')}}
</td> </td>
<td class="text-right">
<a class="action" (click)="confirm(promotion, true)">Bestätigen</a><br>
<a class="action" (click)="confirm(promotion, false)">Ablehnen</a>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@ -1,8 +1,6 @@
import {Component, ViewChild} from "@angular/core"; import {Component} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router"; import {ActivatedRoute, Router} from "@angular/router";
import {Rank, User} from "../../models/model-interfaces"; import {Promotion, Rank} from "../../models/model-interfaces";
import {NgForm} from "@angular/forms";
import {UserService} from "../../services/user-service/user.service";
import {RankService} from "../../services/rank-service/rank.service"; import {RankService} from "../../services/rank-service/rank.service";
import {PromotionService} from "../../services/promotion-service/promotion.service"; import {PromotionService} from "../../services/promotion-service/promotion.service";
@ -13,84 +11,46 @@ import {PromotionService} from "../../services/promotion-service/promotion.servi
}) })
export class ConfirmPromotionComponent { export class ConfirmPromotionComponent {
@ViewChild(NgForm) form: NgForm;
showForm = false;
showSuccessLabel = false; showSuccessLabel = false;
user: User = {};
newLevel: number;
ranks: Rank[]; ranks: Rank[];
users: User[]; promotions: Promotion[];
uncheckedPromotions = [];
constructor(private router: Router, constructor(private router: Router,
private route: ActivatedRoute, private route: ActivatedRoute,
private userService: UserService,
private rankService: RankService, private rankService: RankService,
private promotionService: PromotionService) { private promotionService: PromotionService) {
} }
ngOnInit() { ngOnInit() {
let currentUser = JSON.parse(localStorage.getItem('currentUser')); let currentUser = JSON.parse(localStorage.getItem('currentUser'));
// show only current users squad members // show only current users fraction promotions
this.userService.findUsers('', undefined, currentUser.squad._id).subscribe(users => {
this.users = users;
});
this.rankService.findRanks('', currentUser.squad.fraction).subscribe(ranks => { this.rankService.findRanks('', currentUser.squad.fraction).subscribe(ranks => {
this.ranks = ranks; this.ranks = ranks;
}); });
this.promotionService.getSquadPromotions(currentUser.squad._id).subscribe(promotions => { this.promotionService.getUnconfirmedPromotions(currentUser.squad.fraction).subscribe(promotions => {
this.uncheckedPromotions = promotions; this.promotions = promotions;
}) })
} }
toggleUser() { confirm(promotion: Promotion, decision: boolean) {
this.showForm = true; const updateObject = {
this.newLevel = this.user.rank.level; _id: promotion._id,
} confirmed: decision ? 1 : 2
addPromotion() {
const promotion = {
"userId": this.user._id,
"oldRankLvl": this.user.rank.level,
"newRankLvl": this.newLevel,
}; };
this.promotionService.requestPromotion(promotion).subscribe(); this.promotionService.updatePromotion(updateObject).subscribe(res => {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.promotionService.getUnconfirmedPromotions(currentUser.squad.fraction).subscribe(promotions => {
this.promotions = promotions;
this.showSuccessLabel = true; this.showSuccessLabel = true;
setTimeout(() => { setTimeout(() => {
this.showSuccessLabel = false; this.showSuccessLabel = false;
}, 2000); }, 2000);
this.showForm = false; });
this.user = {}; });
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.promotionService.getSquadPromotions(currentUser.squad._id).subscribe(promotions => {
this.uncheckedPromotions = promotions;
})
}
cancel() {
this.router.navigate(['..'], {relativeTo: this.route});
return false;
}
/**
* compare ngValue with ngModel to assign selected element
*/
equals(o1: User, o2: User) {
if (o1 && o2) {
return o1._id === o2._id;
}
} }
} }

View File

@ -27,11 +27,7 @@ export class LoginService {
signUp(username: string, password: string, secret: string) { signUp(username: string, password: string, secret: string) {
return this.http.post(this.config.apiUrl + this.config.apiSignupPath, {username: username, password: password, secret: secret}) return this.http.post(this.config.apiUrl + this.config.apiSignupPath, {username: username, password: password, secret: secret})
.map((response: Response) => { .map((response: Response) => {
// login successful if there's a jwt token in the response
let user = response.json();
if (user) {
//TODO
}
}); });
} }

View File

@ -10,6 +10,11 @@ export class PromotionService {
private config: AppConfig) { private config: AppConfig) {
} }
getUnconfirmedPromotions(fraction?: string) {
return this.http.get(this.config.apiUrl + this.config.apiPromotionPath + '?inProgress=true&fractFilter=' + fraction)
.map(res => res.json())
}
getSquadPromotions(squadId: string) { getSquadPromotions(squadId: string) {
return this.http.get(this.config.apiUrl + this.config.apiPromotionPath + '?squadId=' + squadId) return this.http.get(this.config.apiUrl + this.config.apiPromotionPath + '?squadId=' + squadId)
.map(res => res.json()) .map(res => res.json())
@ -19,6 +24,11 @@ export class PromotionService {
return this.http.post(this.config.apiUrl + this.config.apiPromotionPath, promotion) return this.http.post(this.config.apiUrl + this.config.apiPromotionPath, promotion)
} }
updatePromotion(promotion) {
return this.http.patch(this.config.apiUrl + this.config.apiPromotionPath + '/' + promotion._id, promotion)
.map(res => res.json())
}
deletePromotion(promotionId) { deletePromotion(promotionId) {
return this.http.delete(this.config.apiUrl + this.config.apiPromotionPath + promotionId) return this.http.delete(this.config.apiUrl + this.config.apiPromotionPath + promotionId)
} }

View File

@ -92,7 +92,7 @@
<a class="small text-nowrap">{{award.date | date: 'dd.MM.yyyy'}}</a> <a class="small text-nowrap">{{award.date | date: 'dd.MM.yyyy'}}</a>
</td> </td>
<td class="text-center"> <td class="text-center">
{{award.confirmed? 'Bestätigt' : 'In Bearbeitung'}} {{award.confirmed === 0? 'In Bearbeitung' : (award.confirmed === 1? 'Genehmigt' : 'Abgelehnt')}}
</td> </td>
<td class="text-center"> <td class="text-center">
<span class="glyphicon glyphicon-trash trash" title="Löschen" (click)="deleteAwarding(award._id)"></span> <span class="glyphicon glyphicon-trash trash" title="Löschen" (click)="deleteAwarding(award._id)"></span>