Skip to content

Commit

Permalink
Fix admin, chart, create
Browse files Browse the repository at this point in the history
  • Loading branch information
nuuxcode committed Dec 19, 2023
1 parent 7e85371 commit b6ae11d
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 13 deletions.
19 changes: 16 additions & 3 deletions admin/src/views/admin/default/components/TopCustomers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,35 @@ const TopCustomers = () => {
const rentals: Rental[] = rentalsResponse.data;
const users: User[] = usersResponse.data;
console.log("rentals", rentals)
console.log("users", users)
console.log("usersx", users)
console.log("usersx lenght", users.length)
// Count rentals by user
const rentalCounts: { [userId: string]: number } = {};
let num = 0;
rentals.forEach((rental) => {
console.log("---------")
console.log(rental.user_id)
if (rental.user_id in rentalCounts) {
rentalCounts[rental.user_id]++;
} else {
rentalCounts[rental.user_id] = 1;
}
console.log(rentalCounts[rental.user_id])
console.log("lop:", num++)
});
console.log("rentalCounts", rentalCounts)
console.log("rental lenght", rentalCounts.length)
// Sort users by rental count and take top 5
const sortedUsers = users
.sort((a, b) => rentalCounts[b.id] - rentalCounts[a.id])
.sort((a, b) => {
const countA = rentalCounts[a.id] || 0;
const countB = rentalCounts[b.id] || 0;
console.log(`Comparing ${a.id}: ${countA} with ${b.id}: ${countB}`);
return countB - countA;
})
.slice(0, 5);
console.log("sortedUsers", sortedUsers)
console.log("sorteduser lenght", sortedUsers.length)
const chartDataTransform = {
name: "Rents Count",
data: sortedUsers.map((user) => rentalCounts[user.id]),
Expand All @@ -77,7 +90,7 @@ const TopCustomers = () => {
<Card extra="flex flex-col bg-white w-full rounded-3xl py-6 px-2 text-center">
<div className="mb-auto flex items-center justify-between px-6">
<h2 className="text-lg font-bold text-navy-700 dark:text-white">
Top Customers
Top Customersx
</h2>
<button className="!linear z-[1] flex items-center justify-center rounded-lg bg-lightPrimary p-2 text-teal-600 !transition !duration-200 hover:bg-gray-100 active:bg-gray-200 dark:bg-navy-700 dark:text-white dark:hover:bg-white/20 dark:active:bg-white/10">
<MdBarChart className="h-6 w-6" />
Expand Down
11 changes: 8 additions & 3 deletions admin/src/views/admin/user/components/ModelCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,23 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({
const [fields, setFields] = useState([]);
const [formValues, setFormValues] = useState<{ [key: string]: any }>({});


useEffect(() => {
const getFields = async (module: string): Promise<string[]> => {
console.log("getFields")
try {
console.log(`${process.env.REACT_APP_API_URL}${module}s${
module === "user" ? "" : "/" + module
}/2`)
const response = await axios.get(
`${process.env.REACT_APP_API_URL}${module}s${
module === "user" ? "" : "/" + module
}/2`,
}/check`,
{
withCredentials: true,
}
);

console.log("response ",response)
if (response.status !== 200) {
throw new Error("Network response was not ok");
}
Expand All @@ -32,7 +37,7 @@ const ModalCreate: React.FC<{ module: string; children: React.ReactNode }> = ({

const excludedFields = ["created_at", "updated_at", "id"];
fields = fields.filter((field) => !excludedFields.includes(field));

console.log("fields",fields)
return fields;
} catch (error) {
console.error(error);
Expand Down
45 changes: 40 additions & 5 deletions api/prisma/seeds/parks.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,43 @@ const prisma = new PrismaClient();
export async function seedParks() {
const createdParks = [];

for (let i = 1; i <= 20; i++) {
const park = createRandomPark(i);
const moroccanCities = [
'Casablanca',
'Rabat',
'Fes',
'Marrakech',
'Tangier',
'Agadir',
'Meknes',
'Oujda',
'Kenitra',
'Tetouan',
'Safi',
'El Jadida',
'Taza',
'Nador',
'Settat',
'Khouribga',
'Beni Mellal',
'Errachidia',
'Tiznit',
'Larache',
'Ksar El Kebir',
'Guelmim',
'Essaouira',
'Al Hoceima',
'Lagouira',
'Tan-Tan',
'Sidi Ifni',
'Tata',
'Dakhla',
];

// Shuffle the moroccanCities array
const shuffledCities = faker.helpers.shuffle(moroccanCities);

for (let i = 0; i < shuffledCities.length; i++) {
const park = createRandomPark(shuffledCities[i]);
if (!park) {
console.log('Skipping undefined park');
continue;
Expand All @@ -22,9 +57,9 @@ export async function seedParks() {
return createdParks;
}

function createRandomPark(number: number): Partial<Park> | null {
const name = `BikeHub Park ${number}`;
const location = faker.location.streetAddress();
function createRandomPark(city: string): Partial<Park> | null {
const name = `${city} Park`;
const location = faker.address.streetAddress();

if (!name || !location) {
console.log('Undefined name or location:', { name, location });
Expand Down
5 changes: 4 additions & 1 deletion api/prisma/seeds/rentals.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export async function seedRentals(users, bikes) {
continue;
}

for (let i = 0; i < 10; i++) {
// Generate a random number between 10 and 30
const numRentals = faker.number.int({ min: 10, max: 30 });

for (let i = 0; i < numRentals; i++) {
const rental = createRandomRental(user, bikes);
if (!rental) {
console.log('Skipping undefined rental');
Expand Down
2 changes: 1 addition & 1 deletion api/prisma/seeds/users.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker';
const prisma = new PrismaClient();

export async function seedUsers() {
const users = faker.helpers.multiple(createRandomUser, { count: 5 }); const createdUsers = [];
const users = faker.helpers.multiple(createRandomUser, { count: 15 }); const createdUsers = [];

for (const user of users) {
const createdUser = await prisma.user.create({
Expand Down
7 changes: 7 additions & 0 deletions api/src/modules/bike/bike.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ export class BikeController {
return this.bikeService.findAll({});
}

@Get('bike/check')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async getFirstUser(): Promise<BikeModel> {
return this.bikeService.findFirst();
}

@Get('park/:parkId?/:status?/:limit?')
async getBikesByParkAndStatusWithLimit(
@Param('parkId') parkId: string,
Expand Down
3 changes: 3 additions & 0 deletions api/src/modules/bike/bike.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export class BikeService {
});
}

async findFirst(): Promise<Bike> {
return this.prisma.bike.findFirst();
}
async findByStatus(status: string, limit?: number): Promise<Bike[]> {
return this.prisma.bike.findMany({
where: {
Expand Down
7 changes: 7 additions & 0 deletions api/src/modules/park/park.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ export class ParkController {
return this.parkService.findAll({});
}

@Get('park/check')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async getFirstUser(): Promise<ParkModel> {
return this.parkService.findFirst();
}

@Get('park/:id')
async getParkById(@Param('id') id: string): Promise<ParkModel> {
return this.parkService.findOne({ id: Number(id) });
Expand Down
6 changes: 6 additions & 0 deletions api/src/modules/park/park.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export class ParkService {
},
});
}

async findFirst(): Promise<Park> {
return this.prisma.park.findFirst();
}


async findOpenParks(): Promise<Park[]> {
return this.prisma.park.findMany({
where: {
Expand Down
11 changes: 11 additions & 0 deletions api/src/modules/rental/rental.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,19 @@ export class RentalController {
return this.rentalService.findAll({});
}

@Get('rental/check')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async getFirstUser(): Promise<RentalModel> {
console.log("----- check")
return this.rentalService.findFirst();
}

@Get('rental/:id')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async getRentalById(@Param('id') id: string): Promise<RentalModel> {
console.log("----- check12")
return this.rentalService.findOne({ id: Number(id) });
}

Expand All @@ -46,6 +55,8 @@ export class RentalController {
return this.rentalService.findAll({ where: { user_id: Number(id) } });
}



@Post('rental')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
Expand Down
4 changes: 4 additions & 0 deletions api/src/modules/rental/rental.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export class RentalService {
return data;
}

async findFirst(): Promise<Rental> {
return this.prisma.rental.findFirst();
}

async findAll(params: {
skip?: number;
take?: number;
Expand Down
7 changes: 7 additions & 0 deletions api/src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ export class UserController {
return this.userService.users({});
}

@Get('check')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
async getFirstUser(): Promise<User> {
return this.userService.findFirst();
}

@Get(':id')
@Roles(ROLES_ENUM.ADMIN)
@UseGuards(JwtAuthGuard)
Expand Down
4 changes: 4 additions & 0 deletions api/src/modules/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export class UserService {
});
}

async findFirst(): Promise<User | null> {
return this.prisma.user.findFirst();
}

async users(params: {
skip?: number;
take?: number;
Expand Down

0 comments on commit b6ae11d

Please sign in to comment.