/** * iDoklad: dohledani kontaktu podle ICO nebo e-mailu. * * Sluzba: https://services.csbot.cz/apps/idoklad * Endpoint: GET /contacts?filter=(IdentificationNumber~eq~12345678) * * Vzor **vlastni kontroly vstupu**. Manifest umi rict "tohle pole je povinne", * ale ne "aspon jedno z dvojice". Takova pravidla patri do kodu, protoze jen * tam jde napsat citelny duvod. */ export const manifest = { id: 'idoklad.find-contact', name: 'Najít kontakt', description: 'Dohledá odběratele v iDokladu podle IČO nebo e-mailu. Nic nezakládá. ' + 'Výsledek se použije jako ID odběratele při vystavení faktury.', inputs: [ { id: 'identificationNumber', label: 'IČO', type: 'string', required: false, pattern: '^[0-9]{6,12}$', hint: 'Jen číslice. Přesnější než e-mail, hledá se podle něj první.', }, { id: 'email', label: 'E-mail', type: 'string', required: false, hint: 'Použije se, když IČO není k dispozici.', }, ], outputs: [ { id: 'found', label: 'Kontakt nalezen', type: 'boolean', required: true }, { id: 'contactId', label: 'ID kontaktu', type: 'number', required: false }, { id: 'companyName', label: 'Název firmy', type: 'string', required: false }, { id: 'identificationNumber', label: 'IČO', type: 'string', required: false }, { id: 'email', label: 'E-mail', type: 'string', required: false }, { id: 'matchedBy', label: 'Podle čeho se našel', type: 'string', required: true }, ], }; const notFound = { found: false, contactId: null, companyName: null, identificationNumber: null, email: null, matchedBy: 'nenalezeno', }; export async function run(inputs, ctx) { const { unwrap, pick, text, num } = ctx.util; if (!inputs.identificationNumber && !inputs.email) { ctx.fail('Vyplňte IČO nebo e-mail, jinak není podle čeho hledat.'); } /** Jedno hledani podle jednoho pole. Vraci kontakt, nebo null. */ async function search(field, value) { const { body } = await ctx.http.get('/contacts', { query: { filter: `(${field}~eq~${value})`, filtertype: 'and', pageSize: 1 }, }); const items = unwrap(body); return Array.isArray(items) && items.length > 0 ? items[0] : null; } // Poradi je zamer: ICO je jednoznacne, e-mail muze mit vic firem stejny. const attempts = []; if (inputs.identificationNumber) { attempts.push(['IdentificationNumber', inputs.identificationNumber, 'IČO']); } if (inputs.email) attempts.push(['Email', inputs.email, 'e-mail']); for (const [field, value, label] of attempts) { const contact = await search(field, value); if (!contact) { ctx.log(`Podle ${label} ${value} se nic nenašlo.`); continue; } return { found: true, contactId: num(pick(contact, 'id')), companyName: text(pick(contact, 'companyName', 'name')), identificationNumber: text(pick(contact, 'identificationNumber')), email: text(pick(contact, 'email')), matchedBy: label, }; } return notFound; }