Skip to content

Commit

Permalink
Merge pull request #14 from ElyasMehraein/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
ElyasMehraein authored Nov 1, 2024
2 parents 2160779 + a4c73a7 commit f81b324
Show file tree
Hide file tree
Showing 90 changed files with 4,389 additions and 1,891 deletions.
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

# production
/build
/public/fonts
/public/avatars
/public/headers

# misc
.DS_Store
Expand All @@ -38,4 +41,6 @@ yarn-error.log*
next-env.d.ts
>>>>>>> Using-Pages-Router

certificates
certificates
app/api/auth/signup/route.js
components/templates/welcome/Welcome.jsx
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"dalirnet.rtl-markdown"
]
}
193 changes: 188 additions & 5 deletions README.md

Large diffs are not rendered by default.

26 changes: 3 additions & 23 deletions app/CB/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { redirect } from 'next/navigation'
import { cookies } from "next/headers";
import connectToDB from "@/configs/db";
import UserModel from "@/models/User";
import BillModel from "@/models/Bill";


export default async function page() {

export default async function page() {
const token = cookies().get("token")?.value;
const tokenPayLoad = verifyToken(token);
if (!tokenPayLoad) {
Expand All @@ -20,29 +19,10 @@ export default async function page() {
"code"
)
if (!user) {
return {
redirect: {
destination: "/",
}
}
redirect('/')
}
let distinctGuilds = []
await BillModel.find({ isAccept: true })
.then(docs => {
if (docs.length > 0) {
const guilds = docs.map(doc => doc.guild);
distinctGuilds = [...new Set(guilds)];

} else {
console.log('No guilds to show.');
}
})
.catch(err => {
console.error(err);
});

return (
<CreateBusiness distinctGuilds={distinctGuilds} />
<CreateBusiness />
)

}
86 changes: 51 additions & 35 deletions app/[subDirectory]/page.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,90 @@
import connectToDB from '@/configs/db'
import connectToDB from '@/configs/db';
import { cookies } from "next/headers";
import { verifyToken } from "@/controllers/auth";
import { notFound } from 'next/navigation'
import { notFound } from 'next/navigation';
import BillModel from '@/models/Bill';
import BusinessModel from '@/models/Business'
import Business from '@/components/templates/business/business'
import UserModel from '@/models/User'
import Profile from '@/components/templates/Profile/Profile'
import { redirect } from 'next/navigation'
import { POST } from '../api/auth/logout/route';
import BusinessModel from '@/models/Business';
import Business from '@/components/templates/business/business';
import UserModel from '@/models/User';
import Profile from '@/components/templates/Profile/Profile';
import { redirect } from 'next/navigation';
import { GET } from '../api/auth/logout/route';
import BusinessRelationModel from '@/models/BusinessRelation';

export default async function subDirectory({ params }) {

try {
const token = cookies().get("token")?.value;
const tokenPayLoad = verifyToken(token);

connectToDB()
let logedUserCode = null;
connectToDB();
let logedUser = null;

if (tokenPayLoad) {
logedUserCode = JSON.parse(JSON.stringify(await UserModel.findOne(
logedUser = JSON.parse(JSON.stringify(await UserModel.findOne(
{ _id: tokenPayLoad.id },
"-_id code"
))).code;
"-_id code businesses"
).populate([
"businesses",
])));
}

if (isNaN(params.subDirectory)) {

// Find Business with relationships (populated)
const business = JSON.parse(JSON.stringify(await BusinessModel.findOne({
businessName: params.subDirectory
}).populate("workers")));
}).populate([
"workers",
"guild",
])));

if (!business) {
console.log("business not found in DB");
notFound()
notFound();
}

// Find relevant Bills
const bills = JSON.parse(JSON.stringify(await BillModel.find({
from: business._id,
isAccept: true
}).populate("to")));

// Get related businesses for logged-in user (if any)
let relations = JSON.parse(JSON.stringify(await BusinessRelationModel.find({
$or: [
{ provider: business._id },
{ receiver: business._id },
],
}).populate("receiver provider")));

return (
<Business business={business}
logedUserCode={logedUserCode}
<Business
business={business}
logedUser={logedUser}
bills={bills}
relations={relations}
/>
)

}

);

} else {

const user = JSON.parse(JSON.stringify(await UserModel.findOne(
{ code: params.subDirectory },
).populate("businesses")))
const user = JSON.parse(JSON.stringify(await UserModel.findOne(
{ code: params.subDirectory },
).populate("businesses")));

if (!user) {
console.log("user not found in DB");
notFound()
if (!user) {
console.log("user not found in DB");
notFound();
}
return (
<Profile user={user}
logedUser={logedUser}
/>
);
}
return (
<Profile user={user}
logedUserCode={logedUserCode}
/>
)
} catch (err) {
console.error('server error in subDirectory:', err);
POST()
redirect("/w");
}
}

}
2 changes: 1 addition & 1 deletion app/all/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export default function AllBusinesses() {
<ItsAvatar userCodeOrBusinessBrand={business.businessName} isAvatar={business.isAvatar} alt="workers avatar" />
</Avatar>
</ListItemAvatar>
<ListItem dense secondaryAction={<ListItemText sx={{ ml: 5 }} align="right" primary={business.businessBrand} secondary={business.bio} />} >
<ListItem dense secondaryAction={<ListItemText sx={{ ml: 5 }} align="right" primary={business.businessName} secondary={business.bio} />} >
</ListItem>
</ListItemButton>
</List>
Expand Down
80 changes: 80 additions & 0 deletions app/api/BillAccept/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import UserModel from '@/models/User';
import BusinessModel from '@/models/Business';
import BillModel from '@/models/Bill';
import { GET } from "@/app/api/auth/me/route"
import GuildModel from '@/models/Guild';

export async function PUT(req) {
const body = await req.json()
let { billId } = body
const response = await GET(req)
const user = await response.json()

try {
const bill = await BillModel.findById(billId);
if (!bill) {
throw new Error('document not found');
}
if (bill.to.toString() !== user._id.toString()) {
return Response.json(
{ message: `You are not authorized to update the bill ` },
{ status: 403 }
)
}
if (bill.status !== "pending") {
return Response.json(
{ message: "its not pending bill" },
{ status: 400 }
)
}
let guild = await GuildModel.findById(bill.guild);
for (let product of bill.products) {
let theGuildProduct = guild.products.find(guildProduct => guildProduct.productName === product.productName);
if (!theGuildProduct) {
guild.products.push({
productName: product.productName,
unitOfMeasurement: product.unitOfMeasurement,
})
await guild.save()
}
}
let business = await BusinessModel.findById(bill.from);

for (let product of bill.products) {
let theBusinessProduct = business.deliveredProducts.find(businessProduct => businessProduct.productName === product.productName);
let uniqueCustomer = await BillModel.distinct('to', {
productName: bill.productName,
from: bill.from,
});
if (theBusinessProduct) {
theBusinessProduct.totalDelivered += product.amount;
theBusinessProduct.thisYearDelivered += product.amount
theBusinessProduct.uniqueCustomer = uniqueCustomer.length
await business.save()

} else {
business.deliveredProducts.push({
productName: product.productName,
unitOfMeasurement: product.unitOfMeasurement,
totalDelivered: product.amount,
lastYearDelivered: 0,
thisYearDelivered: product.amount,
uniqueCustomer: 1,
});
await business.save()
}
}
bill.status = "accepted";
await bill.save();
console.log(`the bill updated successfully.`);
return Response.json(
{ message: `the bill updated successfully.` },
{ status: 200 }
);
} catch (error) {
console.error(`Error updating the bill:`, error);
Response.json(
{ message: `Error updating the bill `, error },
{ status: 500 })
}
}
8 changes: 4 additions & 4 deletions app/api/AcceptBill/route.js → app/api/BillReject/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export async function PUT(req) {
{ status: 403 }
)
}
if (!bill.isAccept) {
bill.isAccept = true;
if (bill.status == "pending") {
bill.status = "rejected";
await bill.save();
} else {
Response.json(
Expand All @@ -33,7 +33,7 @@ export async function PUT(req) {
let business = await BusinessModel.findById(bill.from);

for (let product of bill.products) {
let theBusinessProduct = business.products.find(businessProduct => businessProduct.productName === product.productName);
let theBusinessProduct = business.deliveredProducts.find(businessProduct => businessProduct.productName === product.productName);
let uniqueCustomer = await BillModel.distinct('to', {
productName: bill.productName,
from: bill.from,
Expand All @@ -45,7 +45,7 @@ export async function PUT(req) {
await business.save()

} else {
business.products.push({
business.deliveredProducts.push({
productName: product.productName,
unitOfMeasurement: product.unitOfMeasurement,
totalDelivered: product.amount,
Expand Down
1 change: 1 addition & 0 deletions app/api/allBusinesses/route.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import connectToDB from "@/configs/db";
import BusinessModel from "@/models/Business";
import GuildModel from "@/models/Guild";


export async function GET(req) {
Expand Down
2 changes: 1 addition & 1 deletion app/api/auth/logout/route.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { cookies } from "next/headers";

export async function POST(req) {
export async function GET(req) {
cookies().delete("token");
return Response.json({ message: "User sign out !!" },{status: 200});
}
22 changes: 11 additions & 11 deletions app/api/auth/signup/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ export async function POST(req, res) {
}
console.log("Entrance data is not empty");


if (!phoneFormatCheck(phone) || !SMSFormatCheck(SMSCode)) {
return Response.json({ message: "Entrance data is not valid!" },{status:402})
}
console.log("phone number and smmcode format validate successfully");
// remove for production
// if (!phoneFormatCheck(phone) || !SMSFormatCheck(SMSCode)) {
// return Response.json({ message: "Entrance data is not valid!" },{status:402})
// }
// console.log("phone number and smmcode format validate successfully");


const isOtpSMSValid = await SMSOtpvalidator(phone, SMSCode)
if (!isOtpSMSValid) {
console.log(res.status);
return Response.json({ message: "SMS Code is not valid" },{status:406})
}
// const isOtpSMSValid = await SMSOtpvalidator(phone, SMSCode)
// if (!isOtpSMSValid) {
// console.log(res.status);
// return Response.json({ message: "SMS Code is not valid" },{status:406})
// }


const phoneHash = createHash("sha256").update(phone + process.env.PAPER).digest("hex");
Expand All @@ -42,7 +42,7 @@ export async function POST(req, res) {
user = await UserModel.create({
phoneHash,
code: nextUserNumber,
userName: "",
userName: "کاربر جدید",
isAvatar:false,
isHeader:false,
bio: "",
Expand Down
Loading

0 comments on commit f81b324

Please sign in to comment.