Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

45 merritt admin delete #49

Merged
merged 8 commits into from
Apr 12, 2023
7 changes: 7 additions & 0 deletions backend/api/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ def create(post: Post, post_svc: PostService = Depends(), usr_svc: UserService =
@api.get("", response_model=list[Post], tags=['Post'])
def getAll(post_svc: PostService = Depends()):
return post_svc.getAll()

@api.delete("/{id}", tags=['Post'])
def delete(id: int, post_svc: PostService = Depends()) -> bool:
try:
return post_svc.delete(id=id)
except:
raise HTTPException(status_code=422, detail=str("Post not found"))
6 changes: 3 additions & 3 deletions backend/entities/post_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
class PostEntity(EntityBase):
__tablename__ = 'posts'

id: Mapped[int] = mapped_column(Integer, primary_key=True)
post_id: Mapped[int] = mapped_column(Integer, primary_key=True)
title: Mapped[str] = mapped_column(String(64), nullable = False, default = '')
content: Mapped[str] = mapped_column(Text, nullable=False, default='')

Expand All @@ -35,7 +35,7 @@ class PostEntity(EntityBase):
def from_model(cls, model: Post, user: UserEntity ) -> Self:
#user_svc: UserPostService = Depends()
return cls(
id=model.id,
post_id=model.id,
title = model.title,
content=model.content,
user = user,
Expand All @@ -49,7 +49,7 @@ def from_model(cls, model: Post, user: UserEntity ) -> Self:
def to_model(self) -> Post:
vote_num = [vote.to_model() for vote in self.votes]
return Post(
id=self.id,
id=self.post_id,
title = self.title,
content=self.content,
user=self.user.to_model(),
Expand Down
2 changes: 1 addition & 1 deletion backend/entities/post_votes_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"post_votes",
EntityBase.metadata,
Column('user_id', ForeignKey('user.id'), primary_key=True),
Column('post_id', ForeignKey('posts.id'), primary_key=True)
Column('post_id', ForeignKey('posts.post_id'), primary_key=True)
)
11 changes: 10 additions & 1 deletion backend/services/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,13 @@ def create(self, post: Post, user: UserEntity) -> Post:
def getAll(self) -> list[Post]:
query = select(PostEntity)
entities = self._session.scalars(query).all()
return [entity.to_model() for entity in entities]
return [entity.to_model() for entity in entities]

def delete(self, id: int) -> bool:
query = select(PostEntity).filter_by(post_id=id)
post = self._session.execute(query).scalar_one()
if (post == None):
raise Exception("Post not found")
self._session.delete(post)
self._session.commit()
return True
2 changes: 1 addition & 1 deletion frontend/src/app/makeforum/makeforum.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ <h3>Make a Forum Post With Resources</h3>
</form>


<button mat-stroked-button class="button" id="back" routerLink="/viewforum">Back</button>
<button mat-stroked-button class="button" id="back" routerLink="/viewforum">Back to Forum</button>
5 changes: 3 additions & 2 deletions frontend/src/app/navigation/navigation.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AuthenticationService } from '../authentication.service';
import { Router } from '@angular/router';
import { Profile, ProfileService } from '../profile/profile.service';
import { PermissionService } from '../permission.service';
import { Post, PostService } from '../post.service';

@Component({
selector: 'app-navigation',
Expand All @@ -34,7 +35,8 @@ export class NavigationComponent implements OnInit, OnDestroy {
private profileService: ProfileService,
private breakpointObserver: BreakpointObserver,
protected navigationService: NavigationTitleService,
protected errorDialog: MatDialog
protected errorDialog: MatDialog,
private postService: PostService
) {
this.profile$ = profileService.profile$;
this.checkinPermission$ = this.permission.check('checkin.create', 'checkin/');
Expand Down Expand Up @@ -73,5 +75,4 @@ export class NavigationComponent implements OnInit, OnDestroy {
.pipe(map(result => result.matches))
.subscribe(isHandset => this.isHandset = isHandset);
}

}
11 changes: 9 additions & 2 deletions frontend/src/app/navigation/navigation.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpErrorResponse } from '@angular/common/http';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

Expand All @@ -19,7 +19,9 @@ export class NavigationService {
private _error: BehaviorSubject<string | null> = new BehaviorSubject<string | null>(null);
public error$ = this._error.asObservable();

constructor() {}
constructor(
private http: HttpClient,
) {}

setTitle(title: string) {
this.title.next(title);
Expand All @@ -37,4 +39,9 @@ export class NavigationService {
this._error.next(`Response: ${e.status} ${e.statusText}\nEndpoint: ${e.url}`);
}

deletePost(id: number) {
console.log(id) // test
return this.http.delete("" + id)
}

}
7 changes: 4 additions & 3 deletions frontend/src/app/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ export class PostService {
return throwError(() => new Error("Unable to Post from user"));
}

// deletePost(id: number) {
// return this.http.delete<Post>("/api/forum/" + id)
// }
deletePost(id: number) {
return this.http.delete<Post>("/api/post/" + id)
// return this.http.delete<Post>("/api/post/" + id) // what we had before (from the backend routes)
}

}
1 change: 1 addition & 0 deletions frontend/src/app/viewforum/viewforum.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ <h1>Forum</h1>
<td>{{ post.user.first_name}}</td>
<td>{{ post.user.last_name}}</td>
<td>{{ post.timestamp }}</td>
<td *ngIf="adminPermission$ | async" > <button (click)="onDelete(post.id)">Delete</button> </td>
</tr>
</tbody>
<a mat-list-item routerLink="/forum">Make a Post</a>
Expand Down
31 changes: 30 additions & 1 deletion frontend/src/app/viewforum/viewforum.component.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,50 @@
import { Component } from '@angular/core';
import { Post, PostService } from '../post.service';
import { Observable } from 'rxjs';
import { PermissionService } from '../permission.service';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
selector: 'app-getforum',
templateUrl: './viewforum.component.html',
styleUrls: ['./viewforum.component.css']
})
export class viewforumComponent {
public adminPermission$: Observable<boolean>;
public post$: Observable<Post[]>;

public static Route = {
path: 'viewforum',
component: viewforumComponent
};

constructor(private postService: PostService) {
constructor(
private postService: PostService,
private permission: PermissionService,
) {
this.post$ = postService.getPosts()
this.adminPermission$ = this.permission.check('admin.view', 'admin/')
}

onDelete(id: number): void {
this.postService
.deletePost(id)
.subscribe({ // stopping here when we use the /api/posts + id route)
next: () => this.onSuccess(),
error: (err) => this.onError(err)
})
}

private onSuccess(): void { // get new posts after deletion
this.post$ = this.postService.getPosts()
}

private onError(err: HttpErrorResponse) {
if (err.error.detail) {
window.alert(err.error.detail);
} else {
console.log(JSON.stringify(err)); // see what error is
}
}

}