1import { Actor, log } from 'apify';
2import { PlaywrightCrawler } from '@crawlee/playwright';
3
4const LIST_URL = 'https://app.edgebuildings.com/project-studies';
5
6function parseNum(v) {
7 if (v === null || v === undefined || v === '') return null;
8 const n = Number.parseFloat(String(v).replace(/[,%\s]/g, ''));
9 return Number.isFinite(n) ? n : null;
10}
11
12function makeSlug(name) {
13 return String(name || '')
14 .normalize('NFD')
15 .replace(/[\u0300-\u036f]/g, '')
16 .toLowerCase()
17 .replace(/[^a-z0-9]+/g, '-')
18 .replace(/^-|-$/g, '');
19}
20
21await Actor.init();
22const input = (await Actor.getInput()) ?? {};
23const {
24 country = '',
25 buildingType = 'ALL',
26 certificationLevel = 'ALL',
27 searchQuery = '',
28 includeDetails = true,
29 maxItems = 10,
30} = input;
31
32const countryNorm = country.trim().toLowerCase();
33const queryNorm = searchQuery.trim().toLowerCase();
34const typeNorm = buildingType !== 'ALL' ? buildingType.trim().toLowerCase() : '';
35const certNorm = certificationLevel !== 'ALL' ? certificationLevel.trim().toLowerCase() : '';
36const hasActiveFilter = Boolean(countryNorm || queryNorm || typeNorm || certNorm);
37
38const capturedProjects = new Map();
39const apiEndpointsSeen = [];
40
41function matchesFilter(p) {
42 if (countryNorm && !(p.country || '').toLowerCase().includes(countryNorm)) return false;
43 if (typeNorm && !(p.buildingType || '').toLowerCase().includes(typeNorm)) return false;
44 if (certNorm && (p.certificationLevel || '').toLowerCase() !== certNorm) return false;
45 if (queryNorm && !(p.projectName || '').toLowerCase().includes(queryNorm)) return false;
46 return true;
47}
48
49const crawler = new PlaywrightCrawler({
50 maxConcurrency: 2,
51 maxRequestRetries: 2,
52 requestHandlerTimeoutSecs: 180,
53 navigationTimeoutSecs: 60,
54 launchContext: { launchOptions: { headless: true } },
55 preNavigationHooks: [
56 async ({ request, page }) => {
57 const label = request.userData.label || 'LIST';
58 if (label !== 'LIST') return;
59
60 page.on('response', async (res) => {
61 try {
62 const ct = (res.headers()['content-type'] || '').toLowerCase();
63 const url = res.url();
64 if (!ct.includes('application/json') || !url.includes('edgebuildings')) return;
65 const data = await res.json().catch(() => null);
66 if (!data) return;
67 apiEndpointsSeen.push(url);
68
69 const arr = Array.isArray(data)
70 ? data
71 : (data.items || data.results || data.data || data.projects || data.projectStudies || []);
72 if (!Array.isArray(arr) || arr.length === 0) return;
73
74 for (const row of arr) {
75 if (!row || typeof row !== 'object') continue;
76 const name = row.projectName || row.name || row.title || row.ProjectName || '';
77 const slug = row.slug || row.urlSlug || row.projectSlug || row.id || '';
78 if (!name && !slug) continue;
79 const key = String(slug || name).toLowerCase();
80 if (!capturedProjects.has(key)) {
81 const finalSlug = slug || makeSlug(name);
82 capturedProjects.set(key, {
83 projectName: String(name || slug),
84 country: String(row.country || row.countryName || row.Country || ''),
85 buildingType: String(row.buildingType || row.subType || row.typology || row.BuildingType || ''),
86 certificationLevel: String(row.certificationLevel || row.edgeLevel || row.level || 'EDGE Certified'),
87 projectUrl: finalSlug ? `https://app.edgebuildings.com/project-studies/${finalSlug}` : LIST_URL,
88 });
89 }
90 }
91 } catch {}
92 });
93 },
94 ],
95 async requestHandler({ request, page }) {
96 const label = request.userData.label || 'LIST';
97
98 if (label === 'LIST') {
99 log.info(`Opening ${LIST_URL} (filters: country="${country}", type="${buildingType}", cert="${certificationLevel}", query="${searchQuery}")`);
100 await page.waitForLoadState('networkidle', { timeout: 35000 }).catch(() => {});
101 await page.waitForTimeout(3000);
102
103 const searchTerm = searchQuery.trim() || country.trim();
104 if (searchTerm) {
105 const searchInput = page.locator('input[type="search"], input[placeholder*="Search" i], input[placeholder*="Project" i]').first();
106 if (await searchInput.count().catch(() => 0)) {
107 log.info(`Applying live search term "${searchTerm}" on page filter input`);
108 await searchInput.fill(searchTerm).catch(() => {});
109 await page.keyboard.press('Enter').catch(() => {});
110 await page.waitForTimeout(2500);
111 }
112 }
113
114 const maxScrolls = hasActiveFilter ? 20 : Math.min(20, Math.max(6, Math.ceil(maxItems / 6)));
115 for (let i = 0; i < maxScrolls; i++) {
116 const domCards = await page.evaluate(() => {
117 const out = [];
118 const seen = new Set();
119
120 const anchors = Array.from(document.querySelectorAll('a[href*="/project-studies/"]'));
121 for (const a of anchors) {
122 const href = a.getAttribute('href') || '';
123 if (href.endsWith('/project-studies') || href.endsWith('/project-studies/')) continue;
124 const fullUrl = href.startsWith('http') ? href : `https://app.edgebuildings.com${href.startsWith('/') ? '' : '/'}${href}`;
125 const txt = (a.innerText || a.parentElement?.innerText || '').trim();
126 const lines = txt.split('\n').map((s) => s.trim()).filter(Boolean);
127 const last = lines[lines.length - 1] || '';
128 const m = last.match(/^(Homes|Apartments|Serviced Apartment|Hotel|Hospitality|Resort|Retail|Industrial|Offices?|Hospitals?|Healthcare|Education|Mixed Use|Warehouse|Light Industry)\s+in\s+(.+)$/i);
129 const name = m && lines.length >= 2 ? lines[lines.length - 2] : (lines[0] || '');
130 if (!name || seen.has(fullUrl)) continue;
131 seen.add(fullUrl);
132 out.push({
133 projectName: name,
134 certificationLevel: lines.some((l) => /zero carbon/i.test(l))
135 ? 'EDGE Zero Carbon'
136 : (lines.some((l) => /advanced/i.test(l)) ? 'EDGE Advanced' : 'EDGE Certified'),
137 buildingType: m ? m[1] : '',
138 country: m ? m[2] : '',
139 projectUrl: fullUrl,
140 });
141 }
142
143 const els = Array.from(document.querySelectorAll('div, article, li'));
144 for (const el of els) {
145 const txt = (el.innerText || '').trim();
146 if (!txt || txt.length > 220 || !/\bin\s+[A-Z]/.test(txt)) continue;
147 const lines = txt.split('\n').map((s) => s.trim()).filter(Boolean);
148 if (lines.length < 2 || lines.length > 5) continue;
149 const last = lines[lines.length - 1];
150 const m = last.match(/^(Homes|Apartments|Serviced Apartment|Hotel|Hospitality|Resort|Retail|Industrial|Offices?|Hospitals?|Healthcare|Education|Mixed Use|Warehouse|Light Industry)\s+in\s+(.+)$/i);
151 if (!m) continue;
152 const name = lines[lines.length - 2];
153 if (!name || seen.has(name.toLowerCase())) continue;
154 seen.add(name.toLowerCase());
155 const slug = name
156 .normalize('NFD')
157 .replace(/[\u0300-\u036f]/g, '')
158 .toLowerCase()
159 .replace(/[^a-z0-9]+/g, '-')
160 .replace(/^-|-$/g, '');
161 out.push({
162 projectName: name,
163 certificationLevel: lines.some((l) => /zero carbon/i.test(l))
164 ? 'EDGE Zero Carbon'
165 : (lines.some((l) => /advanced/i.test(l)) ? 'EDGE Advanced' : 'EDGE Certified'),
166 buildingType: m[1],
167 country: m[2],
168 projectUrl: `https://app.edgebuildings.com/project-studies/${slug}`,
169 });
170 }
171 return out;
172 });
173
174 for (const c of domCards) {
175 const key = c.projectName.toLowerCase();
176 if (!capturedProjects.has(key)) {
177 capturedProjects.set(key, c);
178 }
179 }
180
181 const matchingNow = Array.from(capturedProjects.values()).filter(matchesFilter);
182 if (matchingNow.length >= maxItems) break;
183
184 await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
185 await page.waitForTimeout(1600);
186 }
187
188 const filtered = Array.from(capturedProjects.values()).filter(matchesFilter).slice(0, maxItems);
189 log.info(`Captured ${capturedProjects.size} total projects, ${filtered.length} matched filters. API endpoints seen: ${apiEndpointsSeen.length}`);
190
191 if (!includeDetails) {
192 for (const p of filtered) {
193 await Actor.pushData({ ...p, source: 'IFC EDGE Buildings', scrapedAt: new Date().toISOString() });
194 }
195 return;
196 }
197
198 for (const p of filtered) {
199 await crawler.addRequests([{ url: p.projectUrl, userData: { label: 'DETAIL', summary: p } }]);
200 }
201 return;
202 }
203
204 if (label === 'DETAIL') {
205 const { summary } = request.userData;
206 await page.waitForLoadState('networkidle', { timeout: 25000 }).catch(() => {});
207 await page.waitForTimeout(1800);
208
209 const details = await page.evaluate(() => {
210 const bodyText = (document.body.innerText || '').trim();
211 const isNotFound = /page not found|404/i.test(document.title || '') || bodyText.length < 80;
212 const lines = bodyText.split('\n').map((l) => l.trim()).filter(Boolean);
213 const after = (re) => {
214 for (let i = 0; i < lines.length - 1; i++) {
215 if (re.test(lines[i])) return lines[i + 1];
216 }
217 return '';
218 };
219 const pct = (re) => {
220 for (let i = 0; i < lines.length; i++) {
221 if (re.test(lines[i])) {
222 for (const c of [lines[i], lines[i - 1] || '', lines[i + 1] || '']) {
223 const m = c.match(/(\d+(?:\.\d+)?)\s*%/);
224 if (m) return m[1];
225 }
226 }
227 }
228 return '';
229 };
230 return {
231 isNotFound,
232 h1: document.querySelector('h1, h2')?.innerText?.trim() || '',
233 energySavingsRaw: pct(/^Energy Savings/i),
234 waterSavingsRaw: pct(/^Water Savings/i),
235 materialCarbonSavingsRaw: pct(/Less Embodied Carbon in Materials/i),
236 location: after(/^Location$/i),
237 certificationStage: after(/^Certification Stage$/i),
238 certificationDate: after(/^Certification Date$/i),
239 totalFloorAreaRaw: after(/^Total Floor Area/i),
240 totalCo2SavingsRaw: after(/^Total CO2 Savings|^Total CO₂ Savings/i),
241 clientDetails: after(/^Client Details$/i),
242 edgeAuditor: after(/^EDGE Auditor$/i),
243 certifiedBy: after(/^Certified by$/i),
244 };
245 });
246
247 const hasEsgMetrics = Boolean(
248 details.energySavingsRaw || details.waterSavingsRaw || details.totalFloorAreaRaw || details.clientDetails
249 );
250
251 await Actor.pushData({
252 projectName: (!details.isNotFound && details.h1) ? details.h1 : summary.projectName,
253 certificationLevel: summary.certificationLevel || 'EDGE Certified',
254 buildingType: summary.buildingType,
255 country: summary.country,
256 location: details.location || summary.country || '',
257 certificationStage: details.certificationStage || (hasEsgMetrics ? 'Certified' : 'Published Study'),
258 certificationDate: details.certificationDate || null,
259 totalFloorAreaM2: parseNum(details.totalFloorAreaRaw),
260 totalCo2SavingsTonPerYear: parseNum(details.totalCo2SavingsRaw),
261 energySavingsPct: parseNum(details.energySavingsRaw),
262 waterSavingsPct: parseNum(details.waterSavingsRaw),
263 materialCarbonSavingsPct: parseNum(details.materialCarbonSavingsRaw),
264 clientDetails: details.clientDetails || null,
265 edgeAuditor: details.edgeAuditor || null,
266 certifiedBy: details.certifiedBy || null,
267 detailExtractionStatus: hasEsgMetrics ? 'FULL_ESG_METRICS' : 'SUMMARY_ONLY',
268 projectUrl: request.url,
269 source: 'IFC EDGE Buildings',
270 scrapedAt: new Date().toISOString(),
271 });
272 }
273 },
274});
275
276await crawler.run([{ url: LIST_URL, userData: { label: 'LIST' } }]);
277log.info(`Finished. Total captured: ${capturedProjects.size}`);
278await Actor.exit();