-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeee.java
More file actions
775 lines (640 loc) · 22.1 KB
/
Copy pathcodeee.java
File metadata and controls
775 lines (640 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SignInComponent } from './sign-in/sign-in.component';
import { SignUpComponent } from './sign-up/sign-up.component';
const routes: Routes = [
{ path: 'signin', component: SignInComponent },
{ path: 'signup', component: SignUpComponent },
{ path: '**', redirectTo: 'signin' } // Default route
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 2: Create a Reusable Form Component
This component will be used for both Sign Up and Sign In.
📄 auth-form.component.ts
typescript
Copy
Edit
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-auth-form',
templateUrl: './auth-form.component.html',
styleUrls: ['./auth-form.component.css']
})
export class AuthFormComponent {
@Input() isSignup = false;
@Output() formSubmitted = new EventEmitter<FormGroup>();
authForm: FormGroup;
constructor(private router: Router) {
this.authForm = new FormGroup({
username: new FormControl('', Validators.required),
password: new FormControl('', [Validators.required, Validators.minLength(6)])
});
if (this.isSignup) {
this.authForm.addControl('confirmPassword', new FormControl('', Validators.required));
this.authForm.setValidators(this.passwordMatchValidator);
}
}
passwordMatchValidator(form: FormGroup) {
const password = form.get('password')?.value;
const confirmPassword = form.get('confirmPassword')?.value;
return password === confirmPassword ? null : { passwordMismatch: true };
}
onSubmit() {
if (this.authForm.valid) {
this.formSubmitted.emit(this.authForm);
if (this.isSignup) {
this.router.navigate(['/signin']);
}
}
}
navigate() {
this.router.navigate([this.isSignup ? '/signin' : '/signup']);
}
}
Step 3: Create the Template for the Reusable Form
📄 auth-form.component.html
html
Copy
Edit
<div class="container">
<div class="auth-card">
<h2 class="title">GROCERY STORE <br> <span>MANAGEMENT SYSTEM</span></h2>
<p *ngIf="isSignup" class="description">
Streamline inventory, track orders, manage suppliers, and enhance store operations—all in one place.
</p>
<h3 class="subtitle">{{ isSignup ? 'ACCOUNT SIGN UP' : 'ACCOUNT SIGN IN' }}</h3>
<form [formGroup]="authForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input id="username" formControlName="username" placeholder="Enter username" />
<div class="error" *ngIf="authForm.get('username')?.invalid && authForm.get('username')?.touched">
Username is required
</div>
</div>
<div class="form-group">
<label for="password">Password *</label>
<input id="password" formControlName="password" type="password" placeholder="Enter password" />
<div class="error" *ngIf="authForm.get('password')?.invalid && authForm.get('password')?.touched">
Password must be at least 6 characters
</div>
</div>
<div *ngIf="isSignup" class="form-group">
<label for="confirmPassword">Confirm Password *</label>
<input id="confirmPassword" formControlName="confirmPassword" type="password" placeholder="Confirm password" />
<div class="error" *ngIf="authForm.hasError('passwordMismatch') && authForm.get('confirmPassword')?.touched">
Passwords do not match
</div>
</div>
<button type="submit" [disabled]="authForm.invalid" class="btn">
{{ isSignup ? 'Sign Up' : 'Sign In' }}
</button>
</form>
<p class="link-text">
{{ isSignup ? 'Already have an account?' : "Don't have an account?" }}
<a (click)="navigate()">{{ isSignup ? 'Sign In' : 'Sign Up' }}</a>
</p>
</div>
</div>
Step 4: Create Sign In and Sign Up Components
📄 sign-in.component.ts
typescript
Copy
Edit
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-sign-in',
template: '<app-auth-form [isSignup]="false" (formSubmitted)="handleSignIn($event)"></app-auth-form>'
})
export class SignInComponent {
handleSignIn(form: FormGroup) {
console.log('Sign In Successful', form.value);
}
}
📄 sign-up.component.ts
typescript
Copy
Edit
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-sign-up',
template: '<app-auth-form [isSignup]="true" (formSubmitted)="handleSignUp($event)"></app-auth-form>'
})
export class SignUpComponent {
handleSignUp(form: FormGroup) {
console.log('Sign Up Successful', form.value);
}
}
Step 5: Styling (CSS)
📄 auth-form.component.css
css
Copy
Edit
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: url('/assets/bg.jpg') no-repeat center center;
background-size: cover;
}
.auth-card {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
width: 400px;
text-align: center;
}
.title {
font-size: 22px;
font-weight: bold;
margin-bottom: 10px;
}
.title span {
color: #007bff;
font-weight: bold;
}
.description {
font-size: 14px;
color: #666;
margin-bottom: 20px;
}
.subtitle {
font-size: 18px;
margin-bottom: 20px;
font-weight: 600;
}
.form-group {
margin-bottom: 15px;
text-align: left;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 14px;
}
.btn {
width: 100%;
background-color: #007bff;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
.link-text {
margin-top: 15px;
font-size: 14px;
}
.link-text a {
color: #007bff;
cursor: pointer;
text-decoration: underline;
}
import jakarta.validation.constraints.NotBlank;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class PostRequest {
@NotBlank(message = "Content cannot be empty")
private String content;
private String mediaUrl;
}
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class PostResponse {
private Long id;
private String content;
private String mediaUrl;
private int likes;
private int shares;
private String authorUsername;
}
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findAllByAuthorUserId(Long userId);
}
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
private final UserRepository userRepository;
// Create a new post
public PostResponse createPost(Long userId, PostRequest request) {
Users author = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User does not exist"));
Post newPost = new Post();
newPost.setAuthor(author);
newPost.setContent(request.getContent());
newPost.setMediaUrl(request.getMediaUrl());
return convertToResponse(postRepository.save(newPost));
}
// Edit an existing post (only by the author)
@Transactional
public PostResponse modifyPost(Long userId, Long postId, PostRequest request) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post not found"));
if (!post.getAuthor().getUserId().equals(userId)) {
throw new SecurityException("Unauthorized action");
}
post.setContent(request.getContent());
post.setMediaUrl(request.getMediaUrl());
return convertToResponse(postRepository.save(post));
}
// Retrieve all posts by a specific user
public List<PostResponse> fetchUserPosts(Long userId) {
return postRepository.findAllByAuthorUserId(userId).stream()
.map(this::convertToResponse)
.collect(Collectors.toList());
}
// Remove a post (only by the author)
public void removePost(Long userId, Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post does not exist"));
if (!post.getAuthor().getUserId().equals(userId)) {
throw new SecurityException("Unauthorized action");
}
postRepository.delete(post);
}
// Convert Post entity to DTO
private PostResponse convertToResponse(Post post) {
return new PostResponse(
post.getId(),
post.getContent(),
post.getMediaUrl(),
post.getLikes(),
post.getShares(),
post.getAuthor().getUsername()
);
}
}
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
// Endpoint to create a post
@PostMapping("/{userId}")
public ResponseEntity<PostResponse> createPost(
@PathVariable Long userId,
@Valid @RequestBody PostRequest request) {
return ResponseEntity.ok(postService.createPost(userId, request));
}
// Endpoint to update an existing post
@PutMapping("/{userId}/{postId}")
public ResponseEntity<PostResponse> updatePost(
@PathVariable Long userId,
@PathVariable Long postId,
@Valid @RequestBody PostRequest request) {
return ResponseEntity.ok(postService.modifyPost(userId, postId, request));
}
// Endpoint to get all posts by a specific user
@GetMapping("/{userId}")
public ResponseEntity<List<PostResponse>> getPostsByUser(@PathVariable Long userId) {
return ResponseEntity.ok(postService.fetchUserPosts(userId));
}
// Endpoint to delete a post
@DeleteMapping("/{userId}/{postId}")
public ResponseEntity<String> deletePost(@PathVariable Long userId, @PathVariable Long postId) {
postService.removePost(userId, postId);
return ResponseEntity.ok("Post deleted successfully");
}
}
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleBadRequest(IllegalArgumentException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
@ExceptionHandler(SecurityException.class)
public ResponseEntity<String> handleUnauthorizedAccess(SecurityException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ex.getMessage());
}
}
-------------------------------------------------------------------------------------
1. Follow/Unfollow a User
We'll use the Friend entity for following and unfollowing.
Friend Repository
java
Copy
Edit
import org.springframework.data.jpa.repository.JpaRepository;
public interface FriendRepository extends JpaRepository<Friend, Long> {
boolean existsByFollowerIdAndFollowingId(Users follower, Users following);
void deleteByFollowerIdAndFollowingId(Users follower, Users following);
}
Friend Service
java
Copy
Edit
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class FriendService {
private final FriendRepository friendRepository;
private final UserRepository userRepository;
@Transactional
public void followUser(Long followerId, Long followingId) {
Users follower = getUserById(followerId);
Users following = getUserById(followingId);
if (!friendRepository.existsByFollowerIdAndFollowingId(follower, following)) {
Friend friend = new Friend();
friend.setFollowerId(follower);
friend.setFollowingId(following);
friendRepository.save(friend);
}
}
@Transactional
public void unfollowUser(Long followerId, Long followingId) {
Users follower = getUserById(followerId);
Users following = getUserById(followingId);
friendRepository.deleteByFollowerIdAndFollowingId(follower, following);
}
private Users getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
}
}
Friend Controller
java
Copy
Edit
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class FriendController {
private final FriendService friendService;
@PostMapping("/{followerId}/follow/{followingId}")
public ResponseEntity<String> followUser(@PathVariable Long followerId, @PathVariable Long followingId) {
friendService.followUser(followerId, followingId);
return ResponseEntity.ok("Followed successfully!");
}
@PostMapping("/{followerId}/unfollow/{followingId}")
public ResponseEntity<String> unfollowUser(@PathVariable Long followerId, @PathVariable Long followingId) {
friendService.unfollowUser(followerId, followingId);
return ResponseEntity.ok("Unfollowed successfully!");
}
}
2. Like/Unlike a Post
We'll use the Post entity and manage likes as an integer.
Post Repository
java
Copy
Edit
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository<Post, Long> {
}
Like Service
java
Copy
Edit
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
private final UserRepository userRepository;
@Transactional
public void likePost(Long userId, Long postId) {
Post post = getPostById(postId);
post.setLikes(post.getLikes() + 1);
postRepository.save(post);
}
@Transactional
public void unlikePost(Long userId, Long postId) {
Post post = getPostById(postId);
if (post.getLikes() > 0) {
post.setLikes(post.getLikes() - 1);
postRepository.save(post);
}
}
private Post getPostById(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post not found"));
}
}
Like Controller
java
Copy
Edit
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
@PostMapping("/{userId}/like/{postId}")
public ResponseEntity<String> likePost(@PathVariable Long userId, @PathVariable Long postId) {
postService.likePost(userId, postId);
return ResponseEntity.ok("Post liked!");
}
@PostMapping("/{userId}/unlike/{postId}")
public ResponseEntity<String> unlikePost(@PathVariable Long userId, @PathVariable Long postId) {
postService.unlikePost(userId, postId);
return ResponseEntity.ok("Post unliked!");
}
}
3. Comment on a Post
We'll use the Comments entity to handle user comments.
Comment Repository
java
Copy
Edit
import org.springframework.data.jpa.repository.JpaRepository;
public interface CommentRepository extends JpaRepository<Comments, Long> {
}
Comment Service
java
Copy
Edit
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class CommentService {
private final CommentRepository commentRepository;
private final UserRepository userRepository;
private final PostRepository postRepository;
@Transactional
public void addComment(Long userId, Long postId, String content) {
Users user = getUserById(userId);
Post post = getPostById(postId);
Comments comment = new Comments();
comment.setUser(user);
comment.setPost(post);
comment.setContent(content);
commentRepository.save(comment);
}
private Users getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
}
private Post getPostById(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post not found"));
}
}
Comment Controller
java
Copy
Edit
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/comments")
@RequiredArgsConstructor
public class CommentController {
private final CommentService commentService;
@PostMapping("/{userId}/post/{postId}")
public ResponseEntity<String> addComment(@PathVariable Long userId, @PathVariable Long postId, @RequestParam String content) {
commentService.addComment(userId, postId, content);
return ResponseEntity.ok("Comment added!");
}
}
4. Share a Post
We'll create a new post when a user shares an existing post.
Post Sharing Service
java
Copy
Edit
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class PostSharingService {
private final PostRepository postRepository;
private final UserRepository userRepository;
@Transactional
public void sharePost(Long userId, Long postId) {
Users user = getUserById(userId);
Post originalPost = getPostById(postId);
Post sharedPost = new Post();
sharedPost.setUser(user);
sharedPost.setDescription("Shared Post: " + originalPost.getDescription());
sharedPost.setMediaUrl(originalPost.getMediaUrl());
sharedPost.setShared(true);
sharedPost.setOriginalPost(originalPost);
postRepository.save(sharedPost);
}
private Users getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
}
private Post getPostById(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post not found"));
}
}
Post Sharing Controller
java
Copy
Edit
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/share")
@RequiredArgsConstructor
public class PostSharingController {
private final PostSharingService postSharingService;
@PostMapping("/{userId}/share/{postId}")
public ResponseEntity<String> sharePost(@PathVariable Long userId, @PathVariable Long postId) {
postSharingService.sharePost(userId, postId);
return ResponseEntity.ok("Post shared!");
}
}
1. Report Repository
java
Copy
Edit
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ReportRepository extends JpaRepository<Report, Long> {
List<Report> findByPost(Post post);
}
2. Report Service
java
Copy
Edit
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class ReportService {
private final ReportRepository reportRepository;
private final UserRepository userRepository;
private final PostRepository postRepository;
@Transactional
public void reportPost(Long userId, Long postId, String description) {
Users user = getUserById(userId);
Post post = getPostById(postId);
Report report = new Report();
report.setUser(user);
report.setPost(post);
report.setDescription(description);
report.setStatus(Status.PENDING);
reportRepository.save(report);
}
private Users getUserById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
}
private Post getPostById(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Post not found"));
}
}
3. Report Controller
java
Copy
Edit
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/reports")
@RequiredArgsConstructor
public class ReportController {
private final ReportService reportService;
@PostMapping("/{userId}/report/{postId}")
public ResponseEntity<String> reportPost(
@PathVariable Long userId,
@PathVariable Long postId,
@RequestParam String description) {
reportService.reportPost(userId, postId, description);
return ResponseEntity.ok("Post reported successfully!");
}
}