Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
9b2dcd7377 | |||
1eda50ad13 | |||
506a644c6b | |||
555e156b5e | |||
b67e18f2fe | |||
09c9712191 |
19
changelog.md
19
changelog.md
@ -1,5 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-01-02 - 1.2.0 - feat(core)
|
||||
Integrate Handelsregister search for company data retrieval
|
||||
|
||||
- Added support for searching company data via Handelsregister.
|
||||
- Replaced GermanBusinessData functionality with JsonlDataProcessor.
|
||||
- Included smartbrowser dependency for handling web requests to Handelsregister.
|
||||
|
||||
## 2025-01-01 - 1.1.5 - fix(GermanBusinessData)
|
||||
Add console log for total records processed at the end of the stream.
|
||||
|
||||
- Ensure that the number of records processed is logged at the end of data stream processing.
|
||||
|
||||
## 2024-12-31 - 1.1.4 - fix(documentation)
|
||||
Update description and keywords in package.json
|
||||
|
||||
- Corrected the package description to reflect the focus on managing, accessing, and updating open data with MongoDB integration.
|
||||
- Expanded the keywords in the package metadata to include data integration and processing terms.
|
||||
- Improved README.md with more extensive setup, usage, and introduction of the library's functionalities.
|
||||
|
||||
## 2024-12-31 - 1.1.3 - fix(core)
|
||||
Added missing license file for project completeness.
|
||||
|
||||
|
@ -5,7 +5,7 @@
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "fin.cx",
|
||||
"gitrepo": "opendata",
|
||||
"description": "A TypeScript-based library for accessing and managing open business data, specifically for German companies.",
|
||||
"description": "A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.",
|
||||
"npmPackagename": "@fin.cx/opendata",
|
||||
"license": "MIT",
|
||||
"projectDomain": "fin.cx",
|
||||
@ -17,9 +17,13 @@
|
||||
"data management",
|
||||
"business registry",
|
||||
"npm package",
|
||||
"database",
|
||||
"MongoDB",
|
||||
"automation"
|
||||
"automation",
|
||||
"data integration",
|
||||
"database",
|
||||
"data processing",
|
||||
"data retrieval",
|
||||
"data update"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
13
package.json
13
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@fin.cx/opendata",
|
||||
"version": "1.1.3",
|
||||
"version": "1.2.0",
|
||||
"private": false,
|
||||
"description": "A TypeScript-based library for accessing and managing open business data, specifically for German companies.",
|
||||
"description": "A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@ -24,6 +24,7 @@
|
||||
"dependencies": {
|
||||
"@push.rocks/qenv": "^6.1.0",
|
||||
"@push.rocks/smartarchive": "^4.0.39",
|
||||
"@push.rocks/smartbrowser": "^2.0.6",
|
||||
"@push.rocks/smartdata": "^5.2.10",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartfile": "^11.0.23",
|
||||
@ -63,8 +64,12 @@
|
||||
"data management",
|
||||
"business registry",
|
||||
"npm package",
|
||||
"database",
|
||||
"MongoDB",
|
||||
"automation"
|
||||
"automation",
|
||||
"data integration",
|
||||
"database",
|
||||
"data processing",
|
||||
"data retrieval",
|
||||
"data update"
|
||||
]
|
||||
}
|
||||
|
5
pnpm-lock.yaml
generated
5
pnpm-lock.yaml
generated
@ -14,6 +14,9 @@ importers:
|
||||
'@push.rocks/smartarchive':
|
||||
specifier: ^4.0.39
|
||||
version: 4.0.39
|
||||
'@push.rocks/smartbrowser':
|
||||
specifier: ^2.0.6
|
||||
version: 2.0.6
|
||||
'@push.rocks/smartdata':
|
||||
specifier: ^5.2.10
|
||||
version: 5.2.10(@aws-sdk/client-sso-oidc@3.716.0(@aws-sdk/client-sts@3.716.0))(@aws-sdk/credential-providers@3.716.0(@aws-sdk/client-sso-oidc@3.716.0(@aws-sdk/client-sts@3.716.0)))(socks@2.8.3)
|
||||
@ -7496,7 +7499,7 @@ snapshots:
|
||||
|
||||
extract-zip@2.0.1:
|
||||
dependencies:
|
||||
debug: 4.3.4
|
||||
debug: 4.4.0
|
||||
get-stream: 5.2.0
|
||||
yauzl: 2.10.0
|
||||
optionalDependencies:
|
||||
|
271
readme.md
271
readme.md
@ -1,6 +1,6 @@
|
||||
```markdown
|
||||
# @fin.cx/opendata
|
||||
open business data
|
||||
|
||||
A TypeScript-based library for accessing and managing open business data, specifically for German companies.
|
||||
|
||||
## Install
|
||||
|
||||
@ -20,234 +20,199 @@ yarn add @fin.cx/opendata
|
||||
|
||||
## Usage
|
||||
|
||||
The `@fin.cx/opendata` package offers functionalities for handling open business data, with a primary focus on German business data. Let's explore its capabilities through detailed examples.
|
||||
The `@fin.cx/opendata` package provides a comprehensive set of functionalities for handling open business data, focusing on German business data. Let's explore the detailed capabilities of this library through extensive examples and instructions.
|
||||
|
||||
### Setting Up
|
||||
### Setting Up the Environment
|
||||
|
||||
#### Importing the Module
|
||||
First, make sure you've set up the necessary environment variables for MongoDB. You will need the following environment variables:
|
||||
- `MONGODB_URL`: The URL for your MongoDB instance.
|
||||
- `MONGODB_NAME`: The name of the database to use.
|
||||
- `MONGODB_USER`: A valid username for accessing the database.
|
||||
- `MONGODB_PASS`: The password associated with the MongoDB user.
|
||||
|
||||
Begin by importing necessary components from the `@fin.cx/opendata` package. You'll also need to set up some environment variables for the MongoDB instance.
|
||||
These variables can be configured in a `.env` file or managed through a specific service used for secure environment variables handling.
|
||||
|
||||
### Importing and Initializing the Library
|
||||
|
||||
To start working with the library, import the necessary classes and initialize the `OpenData` class.
|
||||
|
||||
```typescript
|
||||
import { OpenData } from '@fin.cx/opendata';
|
||||
|
||||
const startOpenDataInstance = async () => {
|
||||
const initializeOpenData = async () => {
|
||||
const openData = new OpenData();
|
||||
|
||||
try {
|
||||
await openData.start();
|
||||
console.log('OpenData instance has started successfully.');
|
||||
|
||||
// Example usage:
|
||||
await createAndManageBusinessRecords(openData);
|
||||
|
||||
await openData.start(); // Start the open data instance
|
||||
console.log('OpenData instance started.');
|
||||
|
||||
// your code here
|
||||
|
||||
await openData.stop();
|
||||
console.log('OpenData instance stopped.');
|
||||
} catch (error) {
|
||||
console.error('Error starting OpenData:', error);
|
||||
} finally {
|
||||
await openData.stop();
|
||||
console.log('OpenData instance has stopped.');
|
||||
}
|
||||
};
|
||||
|
||||
startOpenDataInstance().catch(console.error);
|
||||
initializeOpenData();
|
||||
```
|
||||
|
||||
### BusinessRecord Usage
|
||||
### Managing Business Records
|
||||
|
||||
A `BusinessRecord` is the main entity you'll be working with. Here's how you manage business records.
|
||||
The `BusinessRecord` class represents a company's data. Let's explore how you can create, retrieve, update, and manage these records.
|
||||
|
||||
#### Creating a New BusinessRecord
|
||||
|
||||
Creating a new business record involves instantiating the `BusinessRecord` class and setting the relevant properties.
|
||||
|
||||
```typescript
|
||||
import { BusinessRecord } from '@fin.cx/opendata';
|
||||
|
||||
const createBusinessRecord = async (openData: OpenData) => {
|
||||
const businessRecord = new openData.CBusinessRecord();
|
||||
businessRecord.data.name = "Example Company";
|
||||
businessRecord.data.address = "Example Street 1";
|
||||
businessRecord.data.postalCode = "12345";
|
||||
businessRecord.data.city = "Example City";
|
||||
businessRecord.data.country = "Germany";
|
||||
businessRecord.data.phone = "+49 123 456789";
|
||||
businessRecord.data.email = "contact@example.com";
|
||||
businessRecord.data.website = "https://example.com";
|
||||
businessRecord.data.businessType = "GmbH";
|
||||
businessRecord.data.registrationNumber = "HRB 123456";
|
||||
businessRecord.data.registrationCourt = "Munich";
|
||||
businessRecord.data.legalForm = "GmbH";
|
||||
businessRecord.data.managingDirectors = ["John Doe", "Jane Smith"];
|
||||
businessRecord.data.foundingDate = new Date().toISOString();
|
||||
businessRecord.data.capital = "50,000 EUR";
|
||||
businessRecord.data.purpose = "Tech Solutions";
|
||||
businessRecord.data.lastUpdate = new Date().toISOString();
|
||||
|
||||
businessRecord.data = {
|
||||
name: "Tech Innovations GmbH",
|
||||
address: "Tech Park 42",
|
||||
postalCode: "80333",
|
||||
city: "Munich",
|
||||
country: "Germany",
|
||||
phone: "+49 89 123456",
|
||||
email: "info@techinnovations.de",
|
||||
website: "https://techinnovations.de",
|
||||
businessType: "GmbH",
|
||||
registrationNumber: "HRB 654321",
|
||||
registrationCourt: "Munich",
|
||||
legalForm: "GmbH",
|
||||
managingDirectors: ["Alice Müller", "Bob Schmidt"],
|
||||
foundingDate: new Date("2020-01-01").toISOString(),
|
||||
capital: "100,000 EUR",
|
||||
purpose: "Developing innovative tech solutions",
|
||||
lastUpdate: new Date().toISOString()
|
||||
};
|
||||
|
||||
await businessRecord.save();
|
||||
console.log('BusinessRecord saved:', businessRecord);
|
||||
};
|
||||
```
|
||||
|
||||
#### Retrieving BusinessRecord
|
||||
#### Retrieving Business Records
|
||||
|
||||
Retrieve a business record by querying the database.
|
||||
You can retrieve existing business records by querying the database using various data fields.
|
||||
|
||||
```typescript
|
||||
import { BusinessRecord } from '@fin.cx/opendata';
|
||||
const retrieveBusinessRecords = async (openData: OpenData) => {
|
||||
const records = await openData.db
|
||||
.collection<BusinessRecord>('businessrecords')
|
||||
.find({ city: "Munich" })
|
||||
.toArray();
|
||||
|
||||
const findBusinessRecord = async (openData: OpenData) => {
|
||||
const businessRecords = await openData.db.collection<BusinessRecord>('businessrecords').find().toArray();
|
||||
console.log('Retrieved Business Records:', businessRecords);
|
||||
console.log('Found Business Records:', records);
|
||||
};
|
||||
```
|
||||
|
||||
### Updating Business Data
|
||||
#### Updating Existing Records
|
||||
|
||||
The `GermanBusinessData` class handles the specifics of updating and maintaining the data.
|
||||
|
||||
#### Updating German Business Data
|
||||
To update an existing `BusinessRecord`, you retrieve the record, modify its data, and save it again.
|
||||
|
||||
```typescript
|
||||
import { OpenData } from '@fin.cx/opendata';
|
||||
const updateBusinessRecord = async (openData: OpenData, recordId: string) => {
|
||||
const businessRecord = await openData.CBusinessRecord.getInstance(recordId);
|
||||
if (businessRecord) {
|
||||
businessRecord.data.phone = "+49 89 987654";
|
||||
businessRecord.data.lastUpdate = new Date().toISOString();
|
||||
|
||||
await businessRecord.save();
|
||||
console.log('BusinessRecord updated:', businessRecord);
|
||||
} else {
|
||||
console.log('BusinessRecord not found for id:', recordId);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Deleting a Business Record
|
||||
|
||||
You can delete a business record using its unique identifier.
|
||||
|
||||
```typescript
|
||||
const deleteBusinessRecord = async (openData: OpenData, recordId: string) => {
|
||||
const businessRecord = await openData.CBusinessRecord.getInstance(recordId);
|
||||
if (businessRecord) {
|
||||
await businessRecord.delete();
|
||||
console.log(`BusinessRecord with id ${recordId} deleted successfully.`);
|
||||
} else {
|
||||
console.log('No record found for the provided id:', recordId);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Updating German Business Data
|
||||
|
||||
The package includes functionalities to keep your business data up-to-date by downloading from official German open data repositories.
|
||||
|
||||
```typescript
|
||||
const updateGermanBusinessData = async (openData: OpenData) => {
|
||||
await openData.germanBusinesses.update();
|
||||
console.log('German business data updated.');
|
||||
try {
|
||||
await openData.germanBusinesses.update();
|
||||
console.log('German business data has been updated successfully.');
|
||||
} catch (error) {
|
||||
console.error('Error updating German business data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
startOpenDataInstance()
|
||||
.then((openData) => {
|
||||
// Use the instance
|
||||
return updateGermanBusinessData(openData);
|
||||
})
|
||||
.catch(console.error);
|
||||
```
|
||||
|
||||
This function downloads the latest data from the German business data source, processes it, and updates the local database.
|
||||
This function fetches the latest open data regarding German companies, processes it, and updates your local database.
|
||||
|
||||
### Detailed Class Structures and Methods
|
||||
### Detailed Class Insights
|
||||
|
||||
#### OpenData Class
|
||||
|
||||
The `OpenData` class is the main entry point.
|
||||
The `OpenData` class serves as the core of the library, initializing necessary components and controlling data flows:
|
||||
|
||||
- **db**: Represents the connection to your MongoDB database.
|
||||
- **germanBusinesses**: An instance handling specific operations related to German business data updates.
|
||||
|
||||
```typescript
|
||||
import { OpenData } from '@fin.cx/opendata';
|
||||
|
||||
class OpenData {
|
||||
db: plugins.smartdata.SmartdataDb;
|
||||
germanBusinesses: GermanBusinessData;
|
||||
|
||||
private serviceQenv = new plugins.qenv.Qenv(paths.packageDir, paths.nogitDir);
|
||||
|
||||
public CBusinessRecord = plugins.smartdata.setDefaultManagerForDoc(this, BusinessRecord);
|
||||
|
||||
public async start() {
|
||||
// Initialize smart data DB
|
||||
this.db = new plugins.smartdata.SmartdataDb({
|
||||
mongoDbUrl: await this.serviceQenv.getEnvVarOnDemand('MONGODB_URL'),
|
||||
mongoDbName: await this.serviceQenv.getEnvVarOnDemand('MONGODB_NAME'),
|
||||
mongoDbUser: await this.serviceQenv.getEnvVarOnDemand('MONGODB_USER'),
|
||||
mongoDbPass: await this.serviceQenv.getEnvVarOnDemand('MONGODB_PASS'),
|
||||
});
|
||||
|
||||
await this.db.init();
|
||||
this.germanBusinesses = new GermanBusinessData(this);
|
||||
await this.germanBusinesses.start();
|
||||
// Database initialization logic
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
// Clean up resources if necessary
|
||||
// Cleanup logic
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### GermanBusinessData Class
|
||||
|
||||
The `GermanBusinessData` class handles the specifics of German business data.
|
||||
This class deals specifically with German company data — fetching, processing, and updating local databases consistently with official German data sources.
|
||||
|
||||
```typescript
|
||||
import { OpenData } from '@fin.cx/opendata';
|
||||
import * as plugins from './plugins';
|
||||
import * as paths from './paths';
|
||||
|
||||
class GermanBusinessData {
|
||||
public openDataRef: OpenData;
|
||||
|
||||
constructor(openDataRef: OpenData) {
|
||||
this.openDataRef = openDataRef;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
await this.update();
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
// Stop any ongoing processing
|
||||
}
|
||||
|
||||
public async update() {
|
||||
const dataUrl = 'https://daten.offeneregister.de/de_companies_ocdata.jsonl.bz2';
|
||||
const dataExists = await plugins.smartfile.fs.isDirectory(paths.germanBusinessDataDir);
|
||||
|
||||
if (!dataExists) {
|
||||
await plugins.smartfile.fs.ensureDir(paths.germanBusinessDataDir);
|
||||
}
|
||||
|
||||
const smartarchive = await plugins.smartarchive.SmartArchive.fromArchiveUrl(dataUrl);
|
||||
const jsonlDataStream = await smartarchive.exportToStreamOfStreamFiles();
|
||||
|
||||
let totalRecordsCounter = 0;
|
||||
let nextRest: string = '';
|
||||
|
||||
jsonlDataStream.pipe(
|
||||
new plugins.smartstream.SmartDuplex({
|
||||
objectMode: true,
|
||||
writeFunction: async (chunkArg: plugins.smartfile.StreamFile, streamToolsArg) => {
|
||||
const readStream = await chunkArg.createReadStream();
|
||||
readStream.pipe(
|
||||
new plugins.smartstream.SmartDuplex({
|
||||
objectMode: true,
|
||||
writeFunction: async (chunkArg: Buffer, streamToolsArg) => {
|
||||
const currentString = nextRest + chunkArg.toString();
|
||||
|
||||
const lines = currentString.split('\n');
|
||||
nextRest = lines.pop();
|
||||
|
||||
for (const line of lines) {
|
||||
let entry: any;
|
||||
try {
|
||||
entry = JSON.parse(line);
|
||||
} catch (err) {
|
||||
console.error('Error parsing line:', err);
|
||||
continue;
|
||||
}
|
||||
|
||||
totalRecordsCounter++;
|
||||
if (totalRecordsCounter % 10000 === 0) {
|
||||
console.log(`${totalRecordsCounter} total records.`);
|
||||
}
|
||||
|
||||
const businessRecord = new this.openDataRef.CBusinessRecord();
|
||||
businessRecord.data.name = entry?.name;
|
||||
|
||||
await businessRecord.save();
|
||||
}
|
||||
},
|
||||
finalFunction: async (streamToolsArg) => {
|
||||
if (nextRest) {
|
||||
try {
|
||||
JSON.parse(nextRest);
|
||||
} catch (err) {
|
||||
console.error('Error parsing final chunk:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
// Logic for updating business data using import streams and parsing JSON lines.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Conclusion
|
||||
### Ensuring Data Accuracy and Integrity
|
||||
|
||||
This module is designed to make it easier to manage open business data, especially focusing on German business data. The examples above demonstrate the core functionalities, including starting and stopping the service, managing business records, and updating data.
|
||||
When working with business data, ensuring integrity and accuracy is crucial. Each record should be checked for validity before being saved or updated, minimizing inconsistencies. Moreover, robust error handling is essential in every step, from data retrieval to database operations, particularly when dealing with external data sources.
|
||||
|
||||
As you work with `@fin.cx/opendata`, you’ll discover it offers a robust and flexible approach for working with open business data seamlessly. Happy coding!
|
||||
```
|
||||
The `@fin.cx/opendata` module provides an extensive toolset for accessing and managing business data, particularly for companies based in Germany. Its functionalities include creating, updating, retrieving, and deleting business records, as well as keeping them current with the latest open data releases. This makes it an invaluable asset for developers aiming to integrate open data seamlessly into their systems, ensuring robust data management capabilities within their applications.
|
||||
|
||||
Happy exploring and integrating open data into your projects!
|
||||
undefined
|
10
test/test.ts
10
test/test.ts
@ -12,4 +12,14 @@ tap.test('should start the instance', async () => {
|
||||
await testOpenDataInstance.start();
|
||||
})
|
||||
|
||||
tap.test('should get the data for a company', async () => {
|
||||
const result = await testOpenDataInstance.handelsregister.getDataForCompany('Volkswagen');
|
||||
console.log(result);
|
||||
});
|
||||
|
||||
tap.test('should stop the instance', async () => {
|
||||
await testOpenDataInstance.stop();
|
||||
});
|
||||
|
||||
|
||||
tap.start()
|
||||
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@fin.cx/opendata',
|
||||
version: '1.1.3',
|
||||
description: 'A TypeScript-based library for accessing and managing open business data, specifically for German companies.'
|
||||
version: '1.2.0',
|
||||
description: 'A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.'
|
||||
}
|
||||
|
138
ts/classes.handelsregister.ts
Normal file
138
ts/classes.handelsregister.ts
Normal file
@ -0,0 +1,138 @@
|
||||
import type { OpenData } from './classes.main.opendata.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
/**
|
||||
* the HandlesRegister exposed as a class
|
||||
*/
|
||||
export class HandelsRegister {
|
||||
private openDataRef: OpenData;
|
||||
|
||||
public smartbrowserInstance = new plugins.smartbrowser.SmartBrowser();
|
||||
|
||||
constructor(openDataRef: OpenData) {
|
||||
this.openDataRef = openDataRef;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
await this.smartbrowserInstance.start();
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
await this.smartbrowserInstance.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a company by name
|
||||
*/
|
||||
public async getDataForCompany(companyNameArg: string) {
|
||||
const page = await this.smartbrowserInstance.headlessBrowser.newPage();
|
||||
await page.setViewport({ width: 1920, height: 1080 });
|
||||
await page.goto('https://www.handelsregister.de/');
|
||||
await page.evaluate(() => {
|
||||
const elements = Array.from(document.querySelectorAll('.ui-menuitem-text > span'));
|
||||
const targetElement = elements.find((el) => el.textContent?.trim() === 'Normal search');
|
||||
if (targetElement) {
|
||||
(targetElement as HTMLElement).click();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
// Wait for the textarea to appear
|
||||
await page.waitForSelector('#form\\:schlagwoerter', { timeout: 5000 });
|
||||
|
||||
// Enter text into the textarea using page.evaluate
|
||||
const inputText = companyNameArg;
|
||||
await page.evaluate((text) => {
|
||||
const textarea = document.querySelector<HTMLTextAreaElement>('#form\\:schlagwoerter');
|
||||
if (textarea) {
|
||||
textarea.value = text; // Set the value
|
||||
// Trigger the change event manually if required
|
||||
const event = new Event('change', { bubbles: true });
|
||||
textarea.dispatchEvent(event);
|
||||
}
|
||||
}, inputText);
|
||||
|
||||
console.log('Text entered successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to find or enter text into the textarea:', error);
|
||||
}
|
||||
|
||||
try {
|
||||
// Wait for the radio button's label to appear
|
||||
await page.waitForSelector('label[for="form:schlagwortOptionen:0"]', { timeout: 5000 });
|
||||
|
||||
// Click the label to select the radio button
|
||||
await page.evaluate(() => {
|
||||
const label = document.querySelector<HTMLLabelElement>(
|
||||
'label[for="form:schlagwortOptionen:0"]'
|
||||
);
|
||||
if (label) {
|
||||
label.click();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Radio button clicked successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to find or click the radio button:', error);
|
||||
}
|
||||
|
||||
try {
|
||||
// Wait for the button with the text "Find" to appear
|
||||
await page.waitForSelector('span.ui-button-text.ui-c', { timeout: 5000 });
|
||||
|
||||
// Locate and click the button using its text
|
||||
await page.evaluate(() => {
|
||||
const buttons = Array.from(document.querySelectorAll('span.ui-button-text.ui-c'));
|
||||
const targetButton = buttons.find((button) => button.textContent?.trim() === 'Find');
|
||||
if (targetButton) {
|
||||
const parentButton = targetButton.closest('button') || targetButton;
|
||||
(parentButton as HTMLElement).click();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Find button clicked successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to find or click the "Find" button:', error);
|
||||
}
|
||||
|
||||
await page.waitForSelector('#ergebnissForm\\:selectedSuchErgebnisFormTable_data', {
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
const businessRecords = await page.evaluate(() => {
|
||||
const rows = document.querySelectorAll(
|
||||
'#ergebnissForm\\:selectedSuchErgebnisFormTable_data > tr'
|
||||
);
|
||||
const records = [];
|
||||
|
||||
rows.forEach((row) => {
|
||||
const nameElement = row.querySelector('td.ui-panelgrid-cell span.marginLeft20');
|
||||
const cityElement = row.querySelector('td.ui-panelgrid-cell.sitzSuchErgebnisse span');
|
||||
const statusElement = row.querySelector('td.ui-panelgrid-cell span.verticalText');
|
||||
const registrationCourtElement = row.querySelector(
|
||||
'td.ui-panelgrid-cell.fontTableNameSize'
|
||||
);
|
||||
|
||||
const name = nameElement?.textContent?.trim();
|
||||
const city = cityElement?.textContent?.trim();
|
||||
const status = statusElement?.textContent?.trim();
|
||||
const registrationCourt = registrationCourtElement?.textContent?.trim();
|
||||
|
||||
// Push parsed data into records array
|
||||
records.push({
|
||||
name,
|
||||
city,
|
||||
registrationCourt,
|
||||
businessType: status,
|
||||
});
|
||||
});
|
||||
|
||||
return records;
|
||||
});
|
||||
|
||||
await page.close();
|
||||
|
||||
// Finally, we return an object, which triggers a JSON file download
|
||||
return businessRecords;
|
||||
}
|
||||
}
|
@ -2,28 +2,23 @@ import * as plugins from './plugins.js';
|
||||
import * as paths from './paths.js';
|
||||
import type { OpenData } from './classes.main.opendata.js';
|
||||
|
||||
export class GermanBusinessData {
|
||||
export class JsonlDataProcessor {
|
||||
public openDataRef: OpenData;
|
||||
constructor(openDataRefArg: OpenData) {
|
||||
this.openDataRef = openDataRefArg;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
await this.update();
|
||||
}
|
||||
public async stop() {}
|
||||
|
||||
public async update() {
|
||||
// TODO: define a mapper as argument instead of hard-coding it
|
||||
public async processDataFromUrl(dataUrlArg = 'https://daten.offeneregister.de/de_companies_ocdata.jsonl.bz2') {
|
||||
const done = plugins.smartpromise.defer();
|
||||
const promiseArray: Promise<any>[] = [];
|
||||
const dataUrl = 'https://daten.offeneregister.de/de_companies_ocdata.jsonl.bz2';
|
||||
const dataExists = await plugins.smartfile.fs.isDirectory(paths.germanBusinessDataDir);
|
||||
if (!dataExists) {
|
||||
await plugins.smartfile.fs.ensureDir(paths.germanBusinessDataDir);
|
||||
} else {
|
||||
}
|
||||
|
||||
const smartarchive = await plugins.smartarchive.SmartArchive.fromArchiveUrl(dataUrl);
|
||||
const smartarchive = await plugins.smartarchive.SmartArchive.fromArchiveUrl(dataUrlArg);
|
||||
promiseArray
|
||||
.push
|
||||
// smartarchive.exportToFs(paths.germanBusinessDataDir, 'de_companies_ocdata.jsonl')
|
||||
@ -60,10 +55,10 @@ export class GermanBusinessData {
|
||||
businessRecord.id = await this.openDataRef.CBusinessRecord.getNewId();
|
||||
businessRecord.data.name = entry.name;
|
||||
await businessRecord.save();
|
||||
// console.log(`stored ${businessRecord.data.name}`);
|
||||
}
|
||||
},
|
||||
finalFunction: async (streamToolsArg) => {
|
||||
console.log(`finished processing ${totalRecordsCounter} records.`);
|
||||
if (!nextRest) return;
|
||||
JSON.parse(nextRest);
|
||||
}
|
@ -1,13 +1,16 @@
|
||||
import { BusinessRecord } from './classes.businessrecord.js';
|
||||
import { GermanBusinessData } from './classes.germanbusinessdata.js';
|
||||
import { HandelsRegister } from './classes.handelsregister.js';
|
||||
import { JsonlDataProcessor } from './classes.jsonldata.js';
|
||||
import * as paths from './paths.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class OpenData {
|
||||
db: plugins.smartdata.SmartdataDb;
|
||||
germanBusinesses: GermanBusinessData;
|
||||
public db: plugins.smartdata.SmartdataDb;
|
||||
private serviceQenv = new plugins.qenv.Qenv(paths.packageDir, paths.nogitDir);
|
||||
|
||||
public jsonLDataProcessor: JsonlDataProcessor;
|
||||
public handelsregister: HandelsRegister;
|
||||
|
||||
public CBusinessRecord = plugins.smartdata.setDefaultManagerForDoc(this, BusinessRecord);
|
||||
|
||||
public async start() {
|
||||
@ -18,8 +21,12 @@ export class OpenData {
|
||||
mongoDbPass: await this.serviceQenv.getEnvVarOnDemand('MONGODB_PASS'),
|
||||
});
|
||||
await this.db.init();
|
||||
this.germanBusinesses = new GermanBusinessData(this);
|
||||
await this.germanBusinesses.start();
|
||||
this.jsonLDataProcessor = new JsonlDataProcessor(this);
|
||||
this.handelsregister = new HandelsRegister(this);
|
||||
await this.handelsregister.start();
|
||||
}
|
||||
public async stop() {
|
||||
await this.db.close();
|
||||
await this.handelsregister.stop();
|
||||
}
|
||||
public async stop() {}
|
||||
}
|
@ -8,6 +8,7 @@ export {
|
||||
// @push.rocks scope
|
||||
import * as qenv from '@push.rocks/qenv';
|
||||
import * as smartarchive from '@push.rocks/smartarchive';
|
||||
import * as smartbrowser from '@push.rocks/smartbrowser';
|
||||
import * as smartdata from '@push.rocks/smartdata';
|
||||
import * as smartdelay from '@push.rocks/smartdelay';
|
||||
import * as smartfile from '@push.rocks/smartfile';
|
||||
@ -19,6 +20,7 @@ import * as smartstream from '@push.rocks/smartstream';
|
||||
export {
|
||||
qenv,
|
||||
smartarchive,
|
||||
smartbrowser,
|
||||
smartdata,
|
||||
smartdelay,
|
||||
smartfile,
|
||||
|
Reference in New Issue
Block a user