const { Analysis, Account, Utils, Resources } = require('@tago-io/sdk');
async function myAnalysis(context, scope) {
const environment = Utils.envToJson(context.environment);
if (!environment.accountToken) {
throw "Environment is missing";
}
let userInfo;
try {
const userId = context.environment.find(item => item.key === '_user_id')?.value;
userInfo = await Resources.run.userInfo(userId);
} catch (error) {
throw error;
}
const serie_number = scope.find(item => item.variable === "serie_number");
const name = scope.find(item => item.variable === "name");
const device_number = scope.find(item => item.variable === "device_number");
const customerTag = userInfo.tags.find(tag => tag.key.startsWith('customer')) || { key: "customer", value: "unknown" };
const deviceType = `temperature_sensor${device_number && device_number.value ? device_number.value : "0"}`;
const deviceData = {
name: name ? name.value : "Default Name",
serie_number: serie_number ? serie_number.value : "No Serie",
tags: [
{ key: "device_type", value: deviceType },
customerTag,
bluedashDevicesTag,
],
connector: "650442f32fbc87000e83",
network: "5fd117be93c650002961",
active: true,
type: "immutable",
chunk_period: "month",
chunk_retention: 12,
};
try {
const account = new Account({ token: environment.accountToken });
const deviceResult = await account.devices.create(deviceData);
context.log(`Device successfully created with name: ${name.value}. ID: ${deviceResult.device_id}`);
const deviceParams = [
{ key: 'limit_telefon', value: '1', sent: true },
];
await Resources.devices.paramSet(deviceResult.device_id, deviceParams);
} catch (ex) {
throw ex;
}
}
module.exports = new Analysis(myAnalysis);