irongit
284 lines10 KBJavaScript
1const Invoices = require("../../model/schema/invoices.js");
2const mongoose = require("mongoose");
3const User = require('../../model/schema/user')
4const Quotes = require("../../model/schema/quotes.js");
5
6
7
8async function getNextAutoIncrementValue() {
9 const num = await Invoices.countDocuments({});
10 return num + 1;
11}
12
13const index = async (req, res) => {
14 query = req.query;
15 query.deleted = false;
16 const user = await User.findById(req.user.userId)
17 if (user?.role !== "superAdmin") {
18 delete query.createBy
19 query.$or = [{ createBy: new mongoose.Types.ObjectId(req.user.userId) }, { assignUser: new mongoose.Types.ObjectId(req.user.userId) }];
20 }
21 try {
22 let result = await Invoices.aggregate([
23 { $match: query },
24 {
25 $lookup: {
26 from: "Contacts",
27 localField: "contact",
28 foreignField: "_id",
29 as: "contactData",
30 },
31 },
32 {
33 $lookup: {
34 from: "Accounts",
35 localField: "account",
36 foreignField: "_id",
37 as: "accountData",
38 },
39 },
40 {
41 $lookup: {
42 from: "User",
43 localField: "createBy",
44 foreignField: "_id",
45 as: "users",
46 },
47 },
48 {
49 $lookup: {
50 from: "User",
51 localField: "modifiedBy",
52 foreignField: "_id",
53 as: "modifiedByUser",
54 },
55 },
56 {
57 $lookup: {
58 from: "User",
59 localField: "assignedTo",
60 foreignField: "_id",
61 as: "assignedToData",
62 },
63 },
64 { $unwind: { path: "$users", preserveNullAndEmptyArrays: true } },
65 { $unwind: { path: "$contactData", preserveNullAndEmptyArrays: true } },
66 { $unwind: { path: "$accountData", preserveNullAndEmptyArrays: true } },
67 { $unwind: { path: '$modifiedByUser', preserveNullAndEmptyArrays: true } },
68 { $unwind: { path: "$assignedToData", preserveNullAndEmptyArrays: true } },
69 { $match: { "users.deleted": false } },
70 {
71 $addFields: {
72 assignUserName: {
73 $cond: {
74 if: '$assignUsers',
75 then: { $concat: ['$assignUsers.firstName', ' ', '$assignUsers.lastName'] },
76 else: { $concat: [''] }
77 }
78 },
79 createdByName: { $concat: ['$users.firstName', ' ', '$users.lastName'] },
80 modifiedUserName: { $concat: ['$modifiedByUser.firstName', ' ', '$modifiedByUser.lastName'] },
81 contactName: { $concat: ['$contactData.firstName', ' ', '$contactData.lastName'] },
82 accountName: '$accountData.name'
83 }
84 },
85 { $project: { users: 0, contactData: 0, accountData: 0, modifiedByUser: 0, assignedToData: 0 } },
86 ]);
87 res.send(result);
88 } catch (error) {
89 console.error("Error:", error);
90 res.status(500).send("Internal Server Error");
91 }
92};
93
94const add = async (req, res) => {
95 try {
96 const nextAutoIncrementValue = await getNextAutoIncrementValue();
97 const result = new Invoices({ ...req.body, invoiceNumber: nextAutoIncrementValue });
98 await result.save();
99 res.status(200).json(result);
100 } catch (err) {
101 console.error("Failed to create Invoices:", err);
102 res.status(400).json({ error: "Failed to create Invoices : ", err });
103 }
104};
105
106const edit = async (req, res) => {
107 try {
108
109 let result = await Invoices.findOneAndUpdate(
110 { _id: req.params.id },
111 { $set: req.body },
112 { new: true }
113 );
114
115 res.status(200).json(result);
116 } catch (err) {
117 console.error("Failed to create Invoices:", err);
118 res.status(400).json({ error: "Failed to create Invoices : ", err });
119 }
120};
121const addMany = async (req, res) => {
122 try {
123 const data = req.body.map((item) => ({
124 ...item,
125 account: item.account ? item.account : null,
126 contact: item.contact ? item.contact : null,
127 }))
128 const inserted = await Invoices.insertMany(data);
129
130 res.status(200).json(inserted);
131 } catch (err) {
132 console.error('Failed to create Invoices :', err);
133 res.status(400).json({ error: 'Failed to create Invoices' });
134 }
135};
136const view = async (req, res) => {
137 try {
138 let response = await Invoices.findOne({ _id: req.params.id });
139 if (!response) return res.status(404).json({ message: "no Data Found." });
140 let result = await Invoices.aggregate([
141 { $match: { _id: response._id } },
142 {
143 $lookup: {
144 from: "Opportunities",
145 localField: "oppotunity",
146 foreignField: "_id",
147 as: "oppotunityData",
148 },
149 },
150 {
151 $lookup: {
152 from: "Contacts",
153 localField: "contact",
154 foreignField: "_id",
155 as: "contactData",
156 },
157 },
158 {
159 $lookup: {
160 from: "Accounts",
161 localField: "account",
162 foreignField: "_id",
163 as: "accountData",
164 },
165 },
166 {
167 $lookup: {
168 from: "User",
169 localField: "createBy",
170 foreignField: "_id",
171 as: "users",
172 },
173 },
174 {
175 $lookup: {
176 from: "User",
177 localField: "modifiedBy",
178 foreignField: "_id",
179 as: "modifiedByUser",
180 },
181 },
182 {
183 $lookup: {
184 from: "User",
185 localField: "assignedTo",
186 foreignField: "_id",
187 as: "assignedToData",
188 },
189 },
190 { $unwind: { path: "$users", preserveNullAndEmptyArrays: true } },
191 { $unwind: { path: "$contactData", preserveNullAndEmptyArrays: true } },
192 { $unwind: { path: "$accountData", preserveNullAndEmptyArrays: true } },
193 { $unwind: { path: '$modifiedByUser', preserveNullAndEmptyArrays: true } },
194 { $unwind: { path: "$assignedToData", preserveNullAndEmptyArrays: true } },
195 { $unwind: { path: "$oppotunityData", preserveNullAndEmptyArrays: true } },
196 { $match: { "users.deleted": false } },
197 {
198 $addFields: {
199 assignUserName: {
200 $cond: {
201 if: '$assignedToData',
202 then: { $concat: ['$assignedToData.firstName', ' ', '$assignedToData.lastName'] },
203 else: { $concat: [''] }
204 }
205 },
206 oppotunityName: '$oppotunityData.opportunityName',
207 createdByName: { $concat: ['$users.firstName', ' ', '$users.lastName'] },
208 modifiedUserName: { $concat: ['$modifiedByUser.firstName', ' ', '$modifiedByUser.lastName'] },
209 contactName: { $concat: ['$contactData.firstName', ' ', '$contactData.lastName'] },
210 accountName: '$accountData.name'
211 }
212 },
213 { $project: { users: 0, contactData: 0, accountData: 0, modifiedByUser: 0, oppotunityData: 0, assignedToData: 0 } },
214 ]);
215 let quotesDetails = await Quotes.aggregate([
216 { $match: { _id: response.quotesId, deleted: false } },
217 {
218 $lookup: {
219 from: "Contacts",
220 localField: "contact",
221 foreignField: "_id",
222 as: "contactData",
223 },
224 },
225 {
226 $lookup: {
227 from: "Accounts",
228 localField: "account",
229 foreignField: "_id",
230 as: "accountData",
231 },
232 },
233 { $unwind: { path: "$contactData", preserveNullAndEmptyArrays: true } },
234 { $unwind: { path: "$accountData", preserveNullAndEmptyArrays: true } },
235 {
236 $addFields: {
237 contactName: { $concat: ['$contactData.firstName', ' ', '$contactData.lastName'] },
238 accountName: '$accountData.name'
239 }
240 },
241 { $project: { contactData: 0, accountData: 0 } },
242
243 ]);
244
245 res.status(200).json({ result: result[0], quotesDetails });
246 } catch (err) {
247 console.log("Error:", err);
248 res.status(400).json({ Error: err });
249 }
250};
251
252const deleteData = async (req, res) => {
253 try {
254 const result = await Invoices.findByIdAndUpdate(req.params.id, {
255 deleted: true,
256 });
257 res.status(200).json({ message: "done", result });
258 } catch (err) {
259 res.status(404).json({ message: "error", err });
260 }
261};
262
263const deleteMany = async (req, res) => {
264 try {
265 const result = await Invoices.updateMany(
266 { _id: { $in: req.body } },
267 { $set: { deleted: true } }
268 );
269
270 if (result?.matchedCount > 0 && result?.modifiedCount > 0) {
271 return res
272 .status(200)
273 .json({ message: "Invoices Removed successfully", result });
274 } else {
275 return res
276 .status(404)
277 .json({ success: false, message: "Failed to remove Invoices" });
278 }
279 } catch (err) {
280 return res.status(404).json({ success: false, message: "error", err });
281 }
282};
283
284module.exports = { index, add, edit, addMany, view, deleteData, deleteMany };