- Установить composer
- composer require smartcat/smartcat-api
- composer install
use SmartCat\Client\SmartCat;
$sc=new SmartCat($login, $password);Получение информации об аккаунте
GET /api/integration/v1/account
$sc->getAccountManager()->accountGetAccountInfo();Получение движков перевода доступных для аккаунта
GET /api/integration/v1/account/mtengines
$sc->getAccountManager()->accountGetMTEnginesForAccount();Получение списка услуг доступных для аккаунта
GET /api/integration/v1/account/lsp/services
$sc->getAccountManager()->accountGetLSPServicesForAccount();Метод получения доступных для назначения исполнителей (фрилансеров из MyTeam или внутренних пользователей из аккаунта)
GET /api/integration/v1/account/assignableExecutives
$sc->getAccountManager()->accountGetAssignableExecutives();Удаление настроек приема уведомлений
DELETE /api/integration/v1/callback
$sc->getCallbackManager()->callbackDelete()Чтение настроек приема уведомлений аккаунта
GET /api/integration/v1/callback
$sc->getCallbackManager()->callbackGet()Создание или обновление настроек приема уведомлений
POST /api/integration/v1/callback
$callback=new CallbackPropertyModel();
$callback->setUrl('https://smartcat.ai');
$res=$sc->getCallbackManager()->callbackUpdate($callback);Чтение последних ошибок отправки (не более 100)
GET /api/integration/v1/callback/lastErrors
$sc->getCallbackManager()->callbackGetLastErrors(['limit'=>$limit])Создать клиента с заданным именем и вернуть его Id.
Если клиент с таким именем существовал, то просто вернуть его Id.
POST /api/integration/v1/client/create
$clientId = $sc->getClientManager()->clientCreateClient('Test client');Получение информации о клиенте аккаунта
GET /api/integration/v1/client/{clientId}
$client = $sc->getClientManager()->clientGetClient($clientId);Устанавливает указанному клиенту указанную сетку скидок
PUT /api/integration/v1/client/{clientId}/set
$client = $sc->getClientManager()->clientSetClientNetRate($clientId, ['netRateId' => $netRateId]);Получить заданный справочник
GET /api/integration/v1/directory
$sc->getDirectoriesManager()->directoriesGet(['type'=>'projectStatus'])Получить поддерживаемые в аккунте форматы для разбора
GET /api/integration/v1/directory/formats
$sc->getDirectoriesManager()->directoriesGetSupportedFormatsForAccount();Удалить один или несколько документов
DELETE /api/integration/v1/document
$sc->getDocumentManager()->documentDelete(['documentIds'=>['id1','id2']])Получить модель документа
GET /api/integration/v1/document
$sc->getDocumentManager()->documentGet(['documentId'=>$docId])Обновить заданный документ
PUT /api/integration/v1/document/update
$bilingualFileImportSettings = new BilingualFileImportSettingsModel();
$bilingualFileImportSettings
->setConfirmMode('none')
->setLockMode('none')
->setTargetSubstitutionMode('all');
$updateDocumentModel = new UploadDocumentPropertiesModel();
$updateDocumentModel->setBilingualFileImportSettings($bilingualFileImportSettings);
$res = $sc->getDocumentManager()->documentUpdate([
'documentId' => $docId,
'updateDocumentModel' => $updateDocumentModel,
'uploadedFile' => [
'fileContent' => fopen('file path', 'r'),
'fileName' => 'file.txt'
]
]);Переименовать заданный документ
PUT /api/integration/v1/document/rename
$sc->getDocumentManager()->documentRename(['documentId'=>$docId,'name'=>'New file name'])Перевести указанный документ, используя переданный файл с переводами
PUT /api/integration/v1/document/translate
$sc->getDocumentManager()->documentTranslate([
'documentId'=>$docId,
'translationFile'=>[
'filePath'=>'Путь к файлу',
'fileName'=>'Имя файла'
]
])Импортировать xliff-файл с переводами документа
PUT /api/integration/v1/document/translateWithXliff
$sc->getDocumentManager()->documentTranslateWithXliff([
'documentId' => $docId,
'confirmTranslation' => true,
'overwriteUpdatedSegments' => true,
'translationFile' => [
'filePath' => 'file path',
'fileName' => 'file.xliff'
]
]);Получить статус задачи добавления перевода документа
GET /api/integration/v1/document/translate/status
$sc->getDocumentManager()->documentGetTranslationStatus(['documentId'=>$docId])Получить подробный отчёт о результатах выполнения импорта переводов
GET /api/integration/v1/document/translate/result
$sc->getDocumentManager()->documentGetTranslationsImportResult(['documentId' => $docsId]);Получить статистику
GET /api/integration/v1/document/statistics
$sc->getDocumentManager()->documentGetStatistics(['documentId' => $docsId]);Разбить документ на равные блоки по количеству слов и назначить каждого из указанных фрилансеров на один блок - устаревший
POST /api/integration/v1/document/assignFreelancers
$sc->getDocumentManager()->documentAssignFreelancersToDocument(
['Abbyyaolid1','Abbyyaolid2'],
[
'documentId' => $documentId,
'stageNumber' => $stageNumber
]
)Разбить документ на равные блоки по количеству слов и назначить каждого из указанных фрилансеров на один блок
POST /api/integration/v1/document/assign
$assignExecutivesRequestModel = new AssignExecutivesRequestModel();
$executive = new Executive();
$executive->setId($freelancerId);
$assignExecutivesRequestModel->setExecutives([$executive]);
$res=$sc->getDocumentManager()->documentAssignExecutives(
$assignExecutivesRequestModel,
[
'documentId' => $docId,
'stageNumber' => $stageNumber
]
);Запросить на экспорт документа(-ов)
POST /api/integration/v1/document/export
$sc->getDocumentExportManager()->documentExportRequestExport(['documentIds'=>['documenId1','documentId2'])Скачать результат экспорта
GET /api/integration/v1/document/export/{taskId}
$sc->getDocumentExportManager()->documentExportDownloadExportResult($taskId);Получить набор глоссариев
GET /api/integration/v1/glossaries
$res = $sc->getGlossaryManager()->glossaryGetGlossaries();Создание начисления фрилансеру
POST /api/integration/v1/invoice/job
$importJobModel = new ImportJobModel();
$importJobModel->setFreelancerId($freelanceId)
->setServiceType('translation')
->setJobDescription('Test invoice')
->setUnitsType('Any text')
->setUnitsAmount(10)
->setPricePerUnit(1)
->setCurrency('usd');
$res=$sc->getInvoiceManager()->invoiceImportJob($importJobModel);Получить все доступные в текущем аккаунте форматы плейсхолдеров
GET /api/integration/v1/placeholders
$res = $sc->getPlaceholderFormatApiManager()->placeholderFormatApiGetPlaceholderFormats();Сохранить набор форматов плейсхолдеров для данного аккаунта
PUT /api/integration/v1/placeholders
$placeHolder1 = new PlaceholderFormatModel();
$placeHolder1->setRegex($regEx1);
$placeHolder2 = new PlaceholderFormatModel();
$placeHolder2->setRegex($regEx2);
$res = $sc->getPlaceholderFormatApiManager()->placeholderFormatApiUpdatePlaceholderFormats([$placeHolder1, $placeHolder2]);Провести валидацию указанного формата плейсхолдеров
GET /api/integration/v1/placeholders/validate
$res = $this->sc->getPlaceholderFormatApiManager()->placeholderFormatApiValidatePlaceholderFormat(['format' => 'Stable\:(\s+)(.+)[\r|]\n']);Удалить проект
DELETE /api/integration/v1/project/{projectId}
$sc->getProjectManager()->projectDelete($projectId)Получить модель проекта
GET /api/integration/v1/project/{projectId}
sc->getProjectManager()->projectGet($projectId)Обновить проект по id - Не рабочий метод API
PUT /api/integration/v1/project/{projectId} - Не работает!
Получить список всех проектов в аккаунте
GET /api/integration/v1/project/list
$sc->getProjectManager()->projectGetAll()Получить статистику и стоимость по проекту
GET /api/integration/v2/project/{projectId}/statistics
$sc->getProjectManager()->projectGetProjectStatistics($projectId);
do {
sleep(5);
$res = $sc->getProjectManager()->projectGetProjectStatistics($projectId);
} while(!is_array($res));Получение статистики по выполненной в проекте работе
GET /api/integration/v1/project/{projectId}/completedWorkStatistics
$res = $sc->getProjectManager()->projectGetCompletedWorkStatistics($projectId);Получение списка идентификаторов ТМ подключенных к проекту
GET /api/integration/v1/project/{projectId}/translationmemories
$res = $sc->getProjectManager()->projectGetProjectTranslationMemories($projectId);Перезаписать набор ТМ подключенных к проекту, набор ТМ одинаков для всех языков перевода проекта
POST /api/integration/v1/project/{projectId}/translationmemories
$translationMemoryForProjectModel = new TranslationMemoryForProjectModel();
$translationMemoryForProjectModel->setId($tmId);
$translationMemoryForProjectModel->setIsWritable(true);
$translationMemoryForProjectModel->setMatchThreshold(100);
$res = $sc->getProjectManager()->projectSetTranslationMemoriesForWholeProject($projectId, [$translationMemoryForProjectModel]);Получить набор подключённых глоссариев к проекту
GET /api/integration/v1/project/{projectId}/glossaries
$res = $sc->getProjectManager()->projectGetGlossaries($projectId);Установить набор подключённых глоссариев к проекту
PUT /api/integration/v1/project/{projectId}/glossaries
$res = $this->sc->getProjectManager()->projectSetGlossaries($projectId, [$glossaryId1, $glossaryId2]);Запустить построение статистики по проекту
POST /api/integration/v1/project/{projectId}/statistics/build
$sc->getProjectManager()->projectBuildStatistics($this->prj->getId());Перезаписать набор ТМ подключенных к проекту, для каждого языка перевода проекта задается свой набор ТМ
POST /api/integration/v1/project/{projectId}/translationmemories/bylanguages
$translationMemoryForProjectModel = new TranslationMemoryForProjectModel();
$translationMemoryForProjectModel->setId($tmId);
$translationMemoryForProjectModel->setIsWritable(true);
$translationMemoryForProjectModel->setMatchThreshold(100);
$tm = new TranslationMemoriesForLanguageModel();
$tm->setLanguage('en');
$tm->setTranslationMemories([$translationMemoryForProjectModel]);
$res = $sc->getProjectManager()->projectSetProjectTranslationMemoriesByLanguages($projectId, [$tm]);Создать проект
POST /api/integration/v1/project/create
$prjCreate = new CreateProjectWithFilesModel();
$prjCreate->setName('Test project');
$prjCreate->setDescription('Test project');
$prjCreate->setSourceLanguage('ru');
$prjCreate->setTargetLanguages(['en']);
$prjCreate->setAssignToVendor(false);
$prjCreate->setUseMT(false);
$prjCreate->setPretranslate(false);
$prjCreate->setUseTranslationMemory(false);
$prjCreate->setAutoPropagateRepetitions(false);
$prjCreate->setIsForTesting(true);
$prjCreate->setWorkflowStages(['translation']);
$prjCreate->attacheFile(fopen(__DIR__.'\Resources\File1_EN.docx'),'File1_EN.docx');
$sc->getProjectManager()->projectCreateProjectWithFiles($prjCreate);Добавить документ к проекту
POST /api/integration/v1/project/document
$bilingualFileImportSettings = new BilingualFileImportSettingsModel();
$bilingualFileImportSettings
->setConfirmMode('none')
->setLockMode('none')
->setTargetSubstitutionMode('all');
$documentModel = new CreateDocumentPropertyWithFilesModel();
$documentModel->setBilingualFileImportSettings($bilingualFileImportSettings);
$documentModel->attachFile(fopen(__DIR__ . '\Resources\File2_EN.docx'), 'File2_EN.docx');
$res = $sc->getProjectManager()->projectAddDocument([
'documentModel' => [$documentModel],
'projectId' => $projectId
]);устаревший вариант:
$sc->getProjectManager()->projectAddDocument([
'projectId'=>$projectId,
'file' => [
'filePath' => '\Resources\File2_EN.docx',
'fileName' => 'File2_EN.docx'
]
]);Добавить новый целевой язык к проекту
POST /api/integration/v1/project/language
$sc->getProjectManager()->projectAddDocument([
'projectId'=>$projectId,
'file' => [
'filePath'=>'path to file',
'fileName'=>'File name'
]
]);Назначить группу исполнителей на конкретный этап документов в проекте
PUT /api/integration/v1/project/{projectId}/assignGroupToWorkflowStage
$sc->getProjectManager()->projectAssignGroupToWorkflowStage($projectId,['groupName'=>'Administrators','workflowStage'=>'translation'])Отменить проект
POST /api/integration/v1/project/cancel
$sc->getProjectManager()->projectCancelProject(['projectId'=>$projectId])Восстановить проект
POST /api/integration/v1/project/restore
$sc->getProjectManager()->projectRestoreProject(['projectId'=>$projectId])Завершить workflow всех документов проекта. Как следствие, статус проекта перейдёт в Completed.
POST /api/integration/v1/project/restore
$sc->getProjectManager()->projectCompleteProject(['projectId' => $this->prj->getId()]);Удалить ТМ
DELETE /api/integration/v1/translationmemory/{tmId}
$sc->getTranslationMemoriesManager()->translationMemoriesRemoveTranslationMemory($tmId)Получить информацию о TM
GET /api/integration/v1/translationmemory/{tmId}
$sc->getTranslationMemoriesManager()->translationMemoriesGetMetaInfo($tmId);Импорт tmx-файлов в TM
POST /api/integration/v1/translationmemory/{tmId}
$sc->getTranslationMemoriesManager()->translationMemoriesImport(
$tmId,
[
'replaceAllContent' => 'true',
'tmxFile' => [
'filePath' => __DIR__ . '\Resources\Space.tmx'
]
]
);Получить пачку доступных ТМ с фильтрацией в аккаунте
GET /api/integration/v1/translationmemory
$thirstRes = $sc->getTranslationMemoriesManager()->translationMemoriesGetTranslationMemoriesBatch([
'lastProcessedId' => '',
'batchSize' => 10
]);
$last = array_pop($thirstRes);
$secondRes = $sc->getTranslationMemoriesManager()->translationMemoriesGetTranslationMemoriesBatch([
'lastProcessedId' => $last->getId(),
'batchSize' => $count
]);Создать пустую ТМ
POST /api/integration/v1/translationmemory
$tm = new CreateTranslationMemoryModel();
$name = 'PHP Unit ' . date('U');
$tm->setName($name);
$tm->setSourceLanguage('ru');
$tm->setTargetLanguages(['en']);
$tm->setDescription("Description: $name");
$tmId = $sc->getTranslationMemoriesManager()->translationMemoriesCreateEmptyTM($tm);Получить коллекцию задач на импорт tmx-файлов
GET /api/integration/v1/translationmemory/task
$sc->getTranslationMemoriesManager()->translationMemoriesGetPendingTasks();Установить массив требуемых целевых языков в ТМ
PUT /api/integration/v1/translationmemory/{tmId}/target
$sc->getTranslationMemoriesManager()->translationMemoriesSetTMTargetLanguages($tmId, ["en", "es"]);Экспорт tmx файлов из базы ТМ
GET /api/integration/v1/translationmemory/{tmId}/file
$sc->getTranslationMemoriesManager()->translationMemoriesExportFile($tmId, ['withTags' => true])Получение матчей из указанной ТМ
POST /api/integration/v1/translationmemory/matches
$tmMatch = new TmMatchesRequest();
$tmMatch->setSourceLanguage('en');
$tmMatch->setTargetLanguage('ru');
$segmentModel = new SegmentModel();
$segmentModel->setText('Test text message');
$segmentModel->setPrevContext('');
$segmentModel->setNextContext('');
$segmentModel->setTags([]);
$tmMatch->setSegmentModel($segmentModel);
$sc->getTranslationMemoriesManager()->translationMemoriesGetTMTranslations($tmMatch, ['tmId' => $tmId]);Удалить указанную задачу на импорт
DELETE /api/integration/v1/translationmemory/task/{taskId}
$sc->getTranslationMemoriesManager()->translationMemoriesRemoveSpecificImportTask($last->getId())Создать нового пользователя с указанными параметрами
POST /api/integration/v1/user
$user = new CreateUserRequest();
$user->setEmail('test@test.com')
->setFirstName('FirstName')
->setLastName('LastName')
->setExternalId('my-external-id')
->setRightsGroup('executive');
$res = $sc->getUserManager()->userCreate($user);Удалить пользователя
DELETE /api/integration/v1/user/{accountUserId}
$sc->getUserManager()->userDelete($smartcatAccountUserId);Получить модель пользователя
GET /api/integration/v1/user/{accountUserId}
$res = $sc->getUserManager()->userGet($smartcatAccountUserId);Обновить данные о пользователе
PUT /api/integration/v1/user/{accountUserId}
$updateModel = new UpdateUserRequest();
$updateModel->setFirstName($newName);
$sc->getUserManager()->userUpdate($smartcatAccountUserId, $updateModel);Получить пользователя по его внешнему идентификатору
GET /api/integration/v1/user/external
$res = $sc->getUserManager()->userGetExternal(['id' => $externalId]);