File size: 6,902 Bytes
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
0159174
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from "crypto";
import Branch from "../models/BranchModel.js";
import Product from "../models/ProductModel.js";
import Customer from "../models/CustomerModel.js";
import Invoice from "../models/InvoiceModel.js";
import Income from "../models/IncomeModel.js";
import Expense from "../models/ExpenseModel.js";
import Supplier from "../models/SupplierModel.js";
import SupplierInvoice from "../models/SupplierInvoiceModel.js";
import Counter from "../models/CounterModel.js";
import User from "../models/UserModel.js";

const DEFAULT_BRANCH_NAME = "Main Branch";
const DEFAULT_BRANCH_CODE = () => `BR-${randomUUID()}`;
const isManagementRole = (role) => ["owner", "admin"].includes(role);

const sanitizeBranchCode = (value) =>
   String(value || "")
      .trim()
      .toUpperCase()
      .replace(/[^A-Z0-9]/g, "")
      .slice(0, 12);

export const ensurePrimaryBranchForTenant = async (tenantId, userId = null) => {
   const existingPrimary = await Branch.findOne({ tenant: tenantId, isPrimary: true });
   if (existingPrimary) {
      return existingPrimary;
   }

   const anyBranch = await Branch.findOne({ tenant: tenantId }).sort({ createdAt: 1 });
   if (anyBranch) {
      anyBranch.isPrimary = true;
      await anyBranch.save();
      return anyBranch;
   }
   const generatedCode = DEFAULT_BRANCH_CODE();
   console.log("🚨 GENERATED CODE:", generatedCode);

   const primaryBranch = await Branch.create({
      tenant: tenantId,
      name: DEFAULT_BRANCH_NAME,
      code: generatedCode,
      isPrimary: true,
      status: "active",
      createdBy: userId || null,
   });

   // Legacy compatibility: migrate pre-branch tenant records to the new primary branch once.
   await Promise.all([
      Product.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Customer.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Invoice.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Income.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Expense.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Supplier.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      SupplierInvoice.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      Counter.updateMany({ tenant: tenantId, branch: null }, { $set: { branch: primaryBranch._id } }),
      User.updateMany({ tenant: tenantId, assignedBranch: null }, { $set: { assignedBranch: primaryBranch._id } }),
   ]);

   return primaryBranch;
};

export const ensureUserBranchAssignment = async (user) => {
   if (!user?.tenant?._id) {
      return null;
   }

   if (user.assignedBranch) {
      return user.assignedBranch;
   }

   const primaryBranch = await ensurePrimaryBranchForTenant(user.tenant._id, user._id);
   user.assignedBranch = primaryBranch._id;
   await user.save();
   await user.populate("assignedBranch");
   return primaryBranch;
};

const getBranchIdFromRequest = (req, source = "query") => {
   if (source === "body") {
      return req.body?.branchId || req.query?.branchId || null;
   }
   return req.query?.branchId || req.body?.branchId || null;
};

export const resolveScopedBranch = async (req, { source = "query" } = {}) => {
   const tenantId = req.user?.tenant?._id;
   if (!tenantId) {
      return {
         tenantId: null,
         includeAllBranches: false,
         branchId: null,
         branchFilter: {},
      };
   }

   const userRole = req.user.role;
   const requestedBranchId = getBranchIdFromRequest(req, source);
   const wantsAllBranches = req.query?.allBranches === "true";

   if (isManagementRole(userRole)) {
      if (!requestedBranchId || wantsAllBranches) {
         return {
            tenantId,
            includeAllBranches: true,
            branchId: null,
            branchFilter: {},
         };
      }

      const branch = await Branch.findOne({
         _id: requestedBranchId,
         tenant: tenantId,
      });

      if (!branch) {
         const err = new Error("BRANCH_NOT_FOUND");
         err.statusCode = 404;
         throw err;
      }

      return {
         tenantId,
         includeAllBranches: false,
         branchId: branch._id,
         branch,
         branchFilter: { branch: branch._id },
      };
   }

   const assignedBranch = await ensureUserBranchAssignment(req.user);
   if (!assignedBranch) {
      const err = new Error("BRANCH_REQUIRED");
      err.statusCode = 403;
      throw err;
   }

   if (requestedBranchId && assignedBranch._id.toString() !== String(requestedBranchId)) {
      const err = new Error("FORBIDDEN_BRANCH_ACCESS");
      err.statusCode = 403;
      throw err;
   }

   return {
      tenantId,
      includeAllBranches: false,
      branchId: assignedBranch._id,
      branch: assignedBranch,
      branchFilter: { branch: assignedBranch._id },
   };
};

export const resolveBranchForWrite = async (req, { preferredBranchId = null } = {}) => {
   const tenantId = req.user?.tenant?._id;
   if (!tenantId) {
      const err = new Error("TENANT_REQUIRED");
      err.statusCode = 403;
      throw err;
   }

   const userRole = req.user.role;
   const desiredBranchId = preferredBranchId || req.body?.branchId || req.query?.branchId || null;

   if (isManagementRole(userRole)) {
      if (desiredBranchId) {
         const branch = await Branch.findOne({
            _id: desiredBranchId,
            tenant: tenantId,
         });
         if (!branch) {
            const err = new Error("BRANCH_NOT_FOUND");
            err.statusCode = 404;
            throw err;
         }
         return branch;
      }
      return ensurePrimaryBranchForTenant(tenantId, req.user._id);
   }

   const assignedBranch = await ensureUserBranchAssignment(req.user);
   if (!assignedBranch) {
      const err = new Error("BRANCH_REQUIRED");
      err.statusCode = 403;
      throw err;
   }

   if (desiredBranchId && String(desiredBranchId) !== assignedBranch._id.toString()) {
      const err = new Error("FORBIDDEN_BRANCH_ACCESS");
      err.statusCode = 403;
      throw err;
   }

   return assignedBranch;
};

export const buildBranchPayload = (branch) => ({
   _id: branch._id,
   tenant: branch.tenant,
   name: branch.name,
   code: branch.code,
   address: branch.address,
   managerName: branch.managerName || "",
   status: branch.status,
   isPrimary: branch.isPrimary,
   createdAt: branch.createdAt,
   updatedAt: branch.updatedAt,
});

export const normalizeBranchCode = sanitizeBranchCode;