From 15325571ec28b8ee4dc4350b4e64d832ff7fabff Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:42:29 +0200 Subject: [PATCH 01/14] feat(posts): unpublish, bulk import and the queue schedule --- src/Model/BulkImportCommit.php | 34 ++++++++++ src/Model/BulkImportPost.php | 26 ++++++++ src/Model/BulkImportRollback.php | 21 ++++++ src/Model/BulkImportRow.php | 55 +++++++++++++++ src/Model/BulkImportValidation.php | 36 ++++++++++ src/Model/PlatformRemoval.php | 31 +++++++++ src/Model/UnpublishResult.php | 29 ++++++++ src/Resource/PostsResource.php | 104 ++++++++++++++++++----------- src/Resource/Resource.php | 40 +++++++++++ tests/PostsTest.php | 77 +++++++++++++++++++++ 10 files changed, 414 insertions(+), 39 deletions(-) create mode 100644 src/Model/BulkImportCommit.php create mode 100644 src/Model/BulkImportPost.php create mode 100644 src/Model/BulkImportRollback.php create mode 100644 src/Model/BulkImportRow.php create mode 100644 src/Model/BulkImportValidation.php create mode 100644 src/Model/PlatformRemoval.php create mode 100644 src/Model/UnpublishResult.php diff --git a/src/Model/BulkImportCommit.php b/src/Model/BulkImportCommit.php new file mode 100644 index 0000000..f7d200e --- /dev/null +++ b/src/Model/BulkImportCommit.php @@ -0,0 +1,34 @@ + $posts */ + private function __construct( + array $raw, + public readonly string $batchId, + public readonly int $created, + /** True when the workspace requires approval and the posts are held. */ + public readonly bool $heldForApproval, + public readonly array $posts, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'batch_id'), + self::int($data, 'created') ?? 0, + self::bool($data, 'held_for_approval') ?? false, + BulkImportPost::listFrom(self::seq($data, 'posts')), + ); + } +} diff --git a/src/Model/BulkImportPost.php b/src/Model/BulkImportPost.php new file mode 100644 index 0000000..5f304f0 --- /dev/null +++ b/src/Model/BulkImportPost.php @@ -0,0 +1,26 @@ + $accounts + * @param array $errors + */ + private function __construct( + array $raw, + public readonly int $row, + public readonly ?string $contentPreview, + public readonly ?string $contentType, + public readonly ?int $threadParts, + public readonly ?DateTimeImmutable $scheduleAt, + public readonly ?array $repeat, + public readonly array $accounts, + public readonly int $labels, + public readonly bool $hasMedia, + public readonly int $mediaCount, + public readonly int $captions, + public readonly array $errors, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'row') ?? 0, + self::str($data, 'content_preview'), + self::str($data, 'content_type'), + self::int($data, 'thread_parts'), + self::date($data, 'schedule_at'), + self::nested($data, 'repeat'), + array_values(array_map(strval(...), self::seq($data, 'accounts'))), + self::int($data, 'labels') ?? 0, + self::bool($data, 'has_media') ?? false, + self::int($data, 'media_count') ?? 0, + self::int($data, 'captions') ?? 0, + array_values(array_map(strval(...), self::seq($data, 'errors'))), + ); + } +} diff --git a/src/Model/BulkImportValidation.php b/src/Model/BulkImportValidation.php new file mode 100644 index 0000000..0d022e5 --- /dev/null +++ b/src/Model/BulkImportValidation.php @@ -0,0 +1,36 @@ + $rows */ + private function __construct( + array $raw, + public readonly int $totalRows, + public readonly int $validRows, + public readonly int $invalidRows, + /** The most data rows one import accepts. */ + public readonly int $maxRows, + public readonly array $rows, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'total_rows') ?? 0, + self::int($data, 'valid_rows') ?? 0, + self::int($data, 'invalid_rows') ?? 0, + self::int($data, 'max_rows') ?? 0, + BulkImportRow::listFrom(self::seq($data, 'rows')), + ); + } +} diff --git a/src/Model/PlatformRemoval.php b/src/Model/PlatformRemoval.php new file mode 100644 index 0000000..6bbdcf5 --- /dev/null +++ b/src/Model/PlatformRemoval.php @@ -0,0 +1,31 @@ + $deliveries */ + private function __construct( + array $raw, + public readonly string $postStatus, + public readonly array $deliveries, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'post_status'), + PlatformRemoval::listFrom(self::seq($data, 'deliveries')), + ); + } +} diff --git a/src/Resource/PostsResource.php b/src/Resource/PostsResource.php index a31d1a8..0dc75a9 100644 --- a/src/Resource/PostsResource.php +++ b/src/Resource/PostsResource.php @@ -12,8 +12,12 @@ use Fopost\Sdk\Model\MediaAsset; use Fopost\Sdk\Model\Page; use Fopost\Sdk\Model\PageMeta; +use Fopost\Sdk\Model\BulkImportCommit; +use Fopost\Sdk\Model\BulkImportRollback; +use Fopost\Sdk\Model\BulkImportValidation; use Fopost\Sdk\Model\Post; use Fopost\Sdk\Model\SocialAccount; +use Fopost\Sdk\Model\UnpublishResult; use Fopost\Sdk\Undefined; use Generator; use InvalidArgumentException; @@ -115,6 +119,8 @@ public function get(string $postId): Post * $status is draft or scheduled; a scheduled post needs $scheduleAt. To * send a post out now, create it and call publish(). $accountGroupId adds * that group's accounts to $accounts, so $accounts may be left empty. + * $schedule of 'queue' drops the post into the next free posting slot + * instead of a time you pick. * * @param string|array|ContentBlock $content * @param array|SocialAccount> $accounts @@ -138,6 +144,7 @@ public function create( array $extra = [], ?string $accountGroupId = null, ?array $files = null, + ?string $schedule = null, ): Post { $body = [ 'workspace_id' => $workspaceId, @@ -149,6 +156,7 @@ public function create( $optional = self::compact([ 'account_group_id' => $accountGroupId, 'schedule_at' => self::iso($scheduleAt), + 'schedule' => $schedule, 'labels' => $labels !== null ? array_values($labels) : null, 'title' => $title, 'summary' => $summary, @@ -193,6 +201,7 @@ public function update( array|Undefined $settings = Undefined::Value, array $extra = [], ?array $files = null, + string|Undefined $schedule = Undefined::Value, ): Post { $body = []; if (!Undefined::is($content)) { @@ -210,6 +219,9 @@ public function update( /** @var string|DateTimeInterface|null $scheduleAt */ $body['schedule_at'] = self::iso($scheduleAt); } + if (!Undefined::is($schedule)) { + $body['schedule'] = $schedule; + } if (!Undefined::is($labels)) { /** @var array $labels */ $body['labels'] = array_values($labels); @@ -311,6 +323,59 @@ public function deliveries(string $postId): array return Delivery::listFrom(self::unwrap($this->http->get("/posts/{$postId}/deliveries"))); } + /** + * Take a published post down on every network it is live on. + * + * A network that cannot delete a live post answers 409, and `removed` is + * false for one that refused. + */ + public function unpublish(string $postId): UnpublishResult + { + return UnpublishResult::fromArray(self::unwrap($this->http->post("/posts/{$postId}/unpublish"))); + } + + /** + * Check a CSV of posts row by row without creating anything. + * + * @param string|array{filename: string, contents: string, mimeType?: string} $file A path or an in-memory file. + */ + public function validateBulkImport(string $workspaceId, string|array $file): BulkImportValidation + { + $body = $this->http->requestMultipart( + 'POST', + '/posts/bulk-import/validate', + ['workspace_id' => $workspaceId], + self::normalizeFiles([$file]), + 'file', + ); + + return BulkImportValidation::fromArray(self::unwrap($body)); + } + + /** + * Create every valid row of the CSV as a post. Needs the `publish` scope as well. + * + * @param string|array{filename: string, contents: string, mimeType?: string} $file A path or an in-memory file. + */ + public function commitBulkImport(string $workspaceId, string|array $file): BulkImportCommit + { + $body = $this->http->requestMultipart( + 'POST', + '/posts/bulk-import/commit', + ['workspace_id' => $workspaceId], + self::normalizeFiles([$file]), + 'file', + ); + + return BulkImportCommit::fromArray(self::unwrap($body)); + } + + /** Delete every post a bulk import created. */ + public function rollbackBulkImport(string $batchId): BulkImportRollback + { + return BulkImportRollback::fromArray(self::unwrap($this->http->delete("/posts/bulk-import/{$batchId}"))); + } + /** * Accept a bare string, one block, or a sequence of blocks. * @@ -349,45 +414,6 @@ private static function normalizeContent(string|array|ContentBlock $content): ar return $out; } - /** - * A path becomes {filename, contents, mimeType}; an array is checked for the same keys. - * - * @param array> $files - * @return array - */ - private static function normalizeFiles(array $files): array - { - $out = []; - foreach ($files as $file) { - if (is_string($file)) { - $contents = is_file($file) ? file_get_contents($file) : false; - if ($contents === false) { - throw new InvalidArgumentException("fopost: cannot read file {$file}"); - } - $mime = function_exists('mime_content_type') ? mime_content_type($file) : false; - $out[] = [ - 'filename' => basename($file), - 'contents' => $contents, - 'mimeType' => is_string($mime) && $mime !== '' ? $mime : 'application/octet-stream', - ]; - continue; - } - $filename = $file['filename'] ?? null; - $contents = $file['contents'] ?? null; - if (!is_string($filename) || $filename === '' || !is_string($contents)) { - throw new InvalidArgumentException('fopost: a file needs a filename and its contents'); - } - $mime = $file['mimeType'] ?? null; - $out[] = [ - 'filename' => $filename, - 'contents' => $contents, - 'mimeType' => is_string($mime) && $mime !== '' ? $mime : 'application/octet-stream', - ]; - } - - return $out; - } - /** @param array $files */ private static function fitMultipart(array $files, int $ceiling): bool { diff --git a/src/Resource/Resource.php b/src/Resource/Resource.php index 07a07ba..6a95c3e 100644 --- a/src/Resource/Resource.php +++ b/src/Resource/Resource.php @@ -9,6 +9,7 @@ use Fopost\Sdk\Model\Model; use Fopost\Sdk\Model\Page; use Fopost\Sdk\Model\PageMeta; +use InvalidArgumentException; abstract class Resource { @@ -62,4 +63,43 @@ protected static function iso(string|DateTimeInterface|null $value): ?string return $value; } + + /** + * A path becomes {filename, contents, mimeType}; an array is checked for the same keys. + * + * @param array> $files + * @return array + */ + protected static function normalizeFiles(array $files): array + { + $out = []; + foreach ($files as $file) { + if (is_string($file)) { + $contents = is_file($file) ? file_get_contents($file) : false; + if ($contents === false) { + throw new InvalidArgumentException("fopost: cannot read file {$file}"); + } + $mime = function_exists('mime_content_type') ? mime_content_type($file) : false; + $out[] = [ + 'filename' => basename($file), + 'contents' => $contents, + 'mimeType' => is_string($mime) && $mime !== '' ? $mime : 'application/octet-stream', + ]; + continue; + } + $filename = $file['filename'] ?? null; + $contents = $file['contents'] ?? null; + if (!is_string($filename) || $filename === '' || !is_string($contents)) { + throw new InvalidArgumentException('fopost: a file needs a filename and its contents'); + } + $mime = $file['mimeType'] ?? null; + $out[] = [ + 'filename' => $filename, + 'contents' => $contents, + 'mimeType' => is_string($mime) && $mime !== '' ? $mime : 'application/octet-stream', + ]; + } + + return $out; + } } diff --git a/tests/PostsTest.php b/tests/PostsTest.php index e7d86a3..6c0a0bb 100644 --- a/tests/PostsTest.php +++ b/tests/PostsTest.php @@ -182,4 +182,81 @@ public function testDeliveriesReturnsDeliveryModels(): void $this->assertSame('d_1', $deliveries[0]->id); $this->assertSame('https://x.test/1', $deliveries[0]->externalUrl); } + + public function testCreateSendsTheQueueSchedule(): void + { + $this->transport->push(200, ['data' => ['id' => 'p_1', 'status' => 'scheduled']]); + + $this->client()->posts()->create(workspaceId: 'w_1', content: 'Hi', accounts: ['a_1'], schedule: 'queue'); + + $body = $this->transport->lastJson(); + $this->assertSame('queue', $body['schedule']); + $this->assertArrayNotHasKey('schedule_at', $body); + } + + public function testUpdateSendsTheQueueSchedule(): void + { + $this->transport->push(200, ['data' => ['id' => 'p_1', 'status' => 'scheduled']]); + + $this->client()->posts()->update('p_1', schedule: 'queue'); + + $this->assertSame('PUT', $this->transport->last()['method']); + $this->assertSame(['schedule' => 'queue'], $this->transport->lastJson()); + } + + public function testUnpublishTakesThePostDown(): void + { + $this->transport->push(200, [ + 'post_status' => 'unpublished', + 'deliveries' => [['account_id' => 'a_1', 'platform' => 'bluesky', 'removed' => true]], + ]); + + $result = $this->client()->posts()->unpublish('p_1'); + + $this->assertSame('POST', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/posts/p_1/unpublish', $this->transport->last()['url']); + $this->assertSame('unpublished', $result->postStatus); + $this->assertTrue($result->deliveries[0]->removed); + $this->assertSame('bluesky', $result->deliveries[0]->platform); + } + + public function testBulkImportSendsTheCsvAsMultipart(): void + { + $this->transport->push(200, [ + 'total_rows' => 2, + 'valid_rows' => 1, + 'invalid_rows' => 1, + 'max_rows' => 500, + 'rows' => [['row' => 2, 'content_preview' => 'Hi', 'errors' => ['unknown account']]], + ]); + $this->transport->push(200, [ + 'batch_id' => 'b_1', + 'created' => 1, + 'held_for_approval' => false, + 'posts' => [['id' => 'p_1', 'schedule_at' => '2026-03-01T09:00:00Z']], + ]); + $this->transport->push(200, ['deleted' => 1]); + + $csv = ['filename' => 'posts.csv', 'contents' => "text\nHi\n", 'mimeType' => 'text/csv']; + $check = $this->client()->posts()->validateBulkImport('w_1', $csv); + $commit = $this->client()->posts()->commitBulkImport('w_1', $csv); + $rollback = $this->client()->posts()->rollbackBulkImport('b_1'); + + $first = $this->transport->requests[0]; + $this->assertSame('POST', $first['method']); + $this->assertSame('https://api.fopost.com/v1/posts/bulk-import/validate', $first['url']); + $this->assertStringStartsWith('multipart/form-data; boundary=', $first['headers']['Content-Type']); + $this->assertStringContainsString('name="workspace_id"' . "\r\n\r\nw_1", (string) $first['body']); + $this->assertStringContainsString('name="file"; filename="posts.csv"', (string) $first['body']); + $this->assertSame(1, $check->invalidRows); + $this->assertSame(['unknown account'], $check->rows[0]->errors); + + $this->assertSame('https://api.fopost.com/v1/posts/bulk-import/commit', $this->transport->requests[1]['url']); + $this->assertSame('b_1', $commit->batchId); + $this->assertSame('2026-03-01', $commit->posts[0]->scheduleAt?->format('Y-m-d')); + + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/posts/bulk-import/b_1', $this->transport->last()['url']); + $this->assertSame(1, $rollback->deleted); + } } From 6dd890ee0b4a2b2353b50b2d2d7441f2e712de4a Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:43:42 +0200 Subject: [PATCH 02/14] feat(queue): posting queue slots, next and preview --- src/Model/QueueMove.php | 28 +++++++++ src/Model/QueueSlot.php | 43 +++++++++++++ src/Model/QueueSlotDeletion.php | 25 ++++++++ src/Model/QueueSlotUpdate.php | 25 ++++++++ src/Resource/QueueResource.php | 104 ++++++++++++++++++++++++++++++++ tests/QueueTest.php | 84 ++++++++++++++++++++++++++ 6 files changed, 309 insertions(+) create mode 100644 src/Model/QueueMove.php create mode 100644 src/Model/QueueSlot.php create mode 100644 src/Model/QueueSlotDeletion.php create mode 100644 src/Model/QueueSlotUpdate.php create mode 100644 src/Resource/QueueResource.php create mode 100644 tests/QueueTest.php diff --git a/src/Model/QueueMove.php b/src/Model/QueueMove.php new file mode 100644 index 0000000..d6d270e --- /dev/null +++ b/src/Model/QueueMove.php @@ -0,0 +1,28 @@ + $moved */ + private function __construct( + array $raw, + public readonly bool $deleted, + public readonly array $moved, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self($data, self::bool($data, 'deleted') ?? false, QueueMove::listFrom(self::seq($data, 'moved'))); + } +} diff --git a/src/Model/QueueSlotUpdate.php b/src/Model/QueueSlotUpdate.php new file mode 100644 index 0000000..6448dbd --- /dev/null +++ b/src/Model/QueueSlotUpdate.php @@ -0,0 +1,25 @@ + $moved */ + private function __construct( + array $raw, + public readonly QueueSlot $slot, + public readonly array $moved, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self($data, QueueSlot::fromArray($data), QueueMove::listFrom(self::seq($data, 'moved'))); + } +} diff --git a/src/Resource/QueueResource.php b/src/Resource/QueueResource.php new file mode 100644 index 0000000..75eb8f9 --- /dev/null +++ b/src/Resource/QueueResource.php @@ -0,0 +1,104 @@ +queue(): the weekly posting slots a queued post lands in. + * + * Create a post with `schedule: 'queue'` to take the next free slot. Needs the `posts` scope. + */ +final class QueueResource extends Resource +{ + /** @return array */ + public function listSlots(string $workspaceId): array + { + return QueueSlot::listFrom(self::unwrap($this->http->get('/queue/slots', ['workspace_id' => $workspaceId]))); + } + + /** `$weekday` is 0 = Sunday … 6 = Saturday; `$time` is HH:MM in `$timezone`; no account means every account. */ + public function createSlot( + string $workspaceId, + int $weekday, + string $time, + string $timezone, + ?string $accountId = null, + ): QueueSlot { + $body = self::compact([ + 'workspace_id' => $workspaceId, + 'weekday' => $weekday, + 'time' => $time, + 'timezone' => $timezone, + 'account_id' => $accountId, + ]); + + return QueueSlot::fromArray(self::unwrap($this->http->post('/queue/slots', $body))); + } + + /** Partial update: only the fields you pass are sent. Posts queued on the slot move with it. */ + public function updateSlot( + string $slotId, + int|Undefined $weekday = Undefined::Value, + string|Undefined $time = Undefined::Value, + string|Undefined $timezone = Undefined::Value, + string|null|Undefined $accountId = Undefined::Value, + ): QueueSlotUpdate { + $body = []; + if (!Undefined::is($weekday)) { + $body['weekday'] = $weekday; + } + if (!Undefined::is($time)) { + $body['time'] = $time; + } + if (!Undefined::is($timezone)) { + $body['timezone'] = $timezone; + } + if (!Undefined::is($accountId)) { + $body['account_id'] = $accountId; + } + + return QueueSlotUpdate::fromArray(self::unwrap($this->http->put("/queue/slots/{$slotId}", $body))); + } + + public function deleteSlot(string $slotId): QueueSlotDeletion + { + return QueueSlotDeletion::fromArray(self::unwrap($this->http->delete("/queue/slots/{$slotId}"))); + } + + /** When the next queued post would go out; null when no slot applies. */ + public function next(string $workspaceId, ?string $accountId = null): ?DateTimeImmutable + { + $query = self::compact(['workspace_id' => $workspaceId, 'account_id' => $accountId]); + $body = self::asArray(self::unwrap($this->http->get('/queue/next', $query))); + $next = $body['next'] ?? null; + + return is_string($next) && $next !== '' ? new DateTimeImmutable($next) : null; + } + + /** + * The next `$count` times the queue would fill, oldest first. + * + * @return array + */ + public function preview(string $workspaceId, ?string $accountId = null, ?int $count = null): array + { + $query = self::compact(['workspace_id' => $workspaceId, 'account_id' => $accountId, 'count' => $count]); + $times = self::unwrap($this->http->get('/queue/preview', $query)); + + $out = []; + foreach (is_array($times) ? $times : [] as $time) { + if (is_string($time) && $time !== '') { + $out[] = new DateTimeImmutable($time); + } + } + + return $out; + } +} diff --git a/tests/QueueTest.php b/tests/QueueTest.php new file mode 100644 index 0000000..a9944ab --- /dev/null +++ b/tests/QueueTest.php @@ -0,0 +1,84 @@ + 'qs_1', + 'workspace_id' => 'w_1', + 'account_id' => null, + 'weekday' => 1, + 'time' => '09:00', + 'timezone' => 'Europe/Zagreb', + 'created_at' => '2026-03-01T09:00:00Z', + ]; + $this->transport->push(200, ['data' => [$slot]]); + $this->transport->push(201, $slot); + $this->transport->push(200, $slot + ['moved' => [[ + 'id' => 'p_1', + 'from' => '2026-03-02T09:00:00Z', + 'to' => '2026-03-02T10:00:00Z', + ]]]); + $this->transport->push(200, ['deleted' => true, 'moved' => []]); + + $queue = $this->client()->queue(); + $slots = $queue->listSlots('w_1'); + $created = $queue->createSlot('w_1', 1, '09:00', 'Europe/Zagreb'); + $updated = $queue->updateSlot('qs_1', time: '10:00'); + $deleted = $queue->deleteSlot('qs_1'); + + $this->assertSame( + 'https://api.fopost.com/v1/queue/slots?workspace_id=w_1', + $this->transport->requests[0]['url'], + ); + $this->assertSame(1, $slots[0]->weekday); + $this->assertNull($slots[0]->accountId); + + $this->assertSame('POST', $this->transport->requests[1]['method']); + $this->assertSame('https://api.fopost.com/v1/queue/slots', $this->transport->requests[1]['url']); + $this->assertSame( + ['workspace_id' => 'w_1', 'weekday' => 1, 'time' => '09:00', 'timezone' => 'Europe/Zagreb'], + json_decode((string) $this->transport->requests[1]['body'], true), + ); + $this->assertSame('qs_1', $created->id); + + $this->assertSame('PUT', $this->transport->requests[2]['method']); + $this->assertSame('https://api.fopost.com/v1/queue/slots/qs_1', $this->transport->requests[2]['url']); + $this->assertSame(['time' => '10:00'], json_decode((string) $this->transport->requests[2]['body'], true)); + $this->assertSame('p_1', $updated->moved[0]->id); + $this->assertSame('2026-03-02T10:00:00+00:00', $updated->moved[0]->to?->format(DATE_ATOM)); + + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/queue/slots/qs_1', $this->transport->last()['url']); + $this->assertTrue($deleted->deleted); + } + + public function testNextAndPreviewReadTheUpcomingTimes(): void + { + $this->transport->push(200, ['next' => '2026-03-02T09:00:00Z']); + $this->transport->push(200, ['data' => ['2026-03-02T09:00:00Z', '2026-03-03T09:00:00Z']]); + $this->transport->push(200, ['next' => null]); + + $next = $this->client()->queue()->next('w_1', 'a_1'); + $preview = $this->client()->queue()->preview('w_1', count: 2); + $none = $this->client()->queue()->next('w_1'); + + $this->assertSame( + 'https://api.fopost.com/v1/queue/next?workspace_id=w_1&account_id=a_1', + $this->transport->requests[0]['url'], + ); + $this->assertSame('2026-03-02', $next?->format('Y-m-d')); + $this->assertSame( + 'https://api.fopost.com/v1/queue/preview?workspace_id=w_1&count=2', + $this->transport->requests[1]['url'], + ); + $this->assertCount(2, $preview); + $this->assertSame('2026-03-03', $preview[1]->format('Y-m-d')); + $this->assertNull($none); + } +} From a8db34d0be5692234657ad03d3d5c29210b28fce Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:43:42 +0200 Subject: [PATCH 03/14] feat(connect-sessions): hosted connect links --- src/Client.php | 18 +++++++ src/Model/ConnectSession.php | 55 +++++++++++++++++++++ src/Resource/ConnectSessionsResource.php | 44 +++++++++++++++++ tests/ConnectSessionsTest.php | 63 ++++++++++++++++++++++++ 4 files changed, 180 insertions(+) create mode 100644 src/Model/ConnectSession.php create mode 100644 src/Resource/ConnectSessionsResource.php create mode 100644 tests/ConnectSessionsTest.php diff --git a/src/Client.php b/src/Client.php index 99ac933..eb2d225 100644 --- a/src/Client.php +++ b/src/Client.php @@ -13,6 +13,7 @@ use Fopost\Sdk\Resource\AiResource; use Fopost\Sdk\Resource\BlogResource; use Fopost\Sdk\Resource\BroadcastsResource; +use Fopost\Sdk\Resource\ConnectSessionsResource; use Fopost\Sdk\Resource\ContactsResource; use Fopost\Sdk\Resource\GoogleBusinessResource; use Fopost\Sdk\Resource\BlogsResource; @@ -22,6 +23,7 @@ use Fopost\Sdk\Resource\LabelsResource; use Fopost\Sdk\Resource\MediaResource; use Fopost\Sdk\Resource\PostsResource; +use Fopost\Sdk\Resource\QueueResource; use Fopost\Sdk\Resource\SequencesResource; use Fopost\Sdk\Resource\ValidateResource; use Fopost\Sdk\Resource\WhatsappResource; @@ -45,6 +47,8 @@ final class Client private readonly HttpClient $http; private readonly PostsResource $posts; + private readonly QueueResource $queue; + private readonly ConnectSessionsResource $connectSessions; private readonly AccountsResource $accounts; private readonly AccountGroupsResource $accountGroups; private readonly WorkspacesResource $workspaces; @@ -83,6 +87,8 @@ public function __construct( $this->http = new HttpClient($key, $baseUrl, $timeout, $maxRetries, $transport); $this->posts = new PostsResource($this->http); + $this->queue = new QueueResource($this->http); + $this->connectSessions = new ConnectSessionsResource($this->http); $this->accounts = new AccountsResource($this->http); $this->accountGroups = new AccountGroupsResource($this->http); $this->workspaces = new WorkspacesResource($this->http); @@ -109,11 +115,23 @@ public function posts(): PostsResource return $this->posts; } + /** The weekly posting slots a post created with `schedule: 'queue'` lands in. */ + public function queue(): QueueResource + { + return $this->queue; + } + public function accounts(): AccountsResource { return $this->accounts; } + /** Hosted connect links for your own users. */ + public function connectSessions(): ConnectSessionsResource + { + return $this->connectSessions; + } + public function accountGroups(): AccountGroupsResource { return $this->accountGroups; diff --git a/src/Model/ConnectSession.php b/src/Model/ConnectSession.php new file mode 100644 index 0000000..8dedd5a --- /dev/null +++ b/src/Model/ConnectSession.php @@ -0,0 +1,55 @@ + $platforms + * @param array{name: ?string, logo_url: ?string}|null $branding + */ + private function __construct( + array $raw, + public readonly string $id, + /** pending, used or expired. */ + public readonly string $status, + public readonly string $externalUserId, + public readonly array $platforms, + public readonly ?string $redirectUrl, + public readonly ?array $branding, + /** The connected account, once the session is used. */ + public readonly ?string $accountId, + /** The hosted link to hand to your user. Present on creation only. */ + public readonly ?string $url, + public readonly ?DateTimeImmutable $expiresAt, + public readonly ?DateTimeImmutable $usedAt, + public readonly ?DateTimeImmutable $createdAt, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'id'), + self::requiredStr($data, 'status'), + self::requiredStr($data, 'external_user_id'), + array_values(array_map(strval(...), self::seq($data, 'platforms'))), + self::str($data, 'redirect_url'), + self::nested($data, 'branding'), + self::str($data, 'account_id'), + self::str($data, 'url'), + self::date($data, 'expires_at'), + self::date($data, 'used_at'), + self::date($data, 'created_at'), + ); + } +} diff --git a/src/Resource/ConnectSessionsResource.php b/src/Resource/ConnectSessionsResource.php new file mode 100644 index 0000000..4116aa1 --- /dev/null +++ b/src/Resource/ConnectSessionsResource.php @@ -0,0 +1,44 @@ +connectSessions(): hosted connect links for your own users. + * + * Create a session, send the user to its `url`, then poll `get()` until the + * status is `used` and `accountId` names the connected account. Needs the + * `accounts` scope. + */ +final class ConnectSessionsResource extends Resource +{ + /** + * @param array $platforms The networks the user may connect. + * @param array{name?: string, logoUrl?: string}|null $branding + */ + public function create( + string $externalUserId, + array $platforms, + ?string $workspaceId = null, + ?string $redirectUrl = null, + ?array $branding = null, + ): ConnectSession { + $body = self::compact([ + 'workspaceId' => $workspaceId, + 'externalUserId' => $externalUserId, + 'platforms' => array_values($platforms), + 'redirectUrl' => $redirectUrl, + 'branding' => $branding, + ]); + + return ConnectSession::fromArray(self::unwrap($this->http->post('/connect-sessions', $body))); + } + + public function get(string $sessionId): ConnectSession + { + return ConnectSession::fromArray(self::unwrap($this->http->get("/connect-sessions/{$sessionId}"))); + } +} diff --git a/tests/ConnectSessionsTest.php b/tests/ConnectSessionsTest.php new file mode 100644 index 0000000..1c9355e --- /dev/null +++ b/tests/ConnectSessionsTest.php @@ -0,0 +1,63 @@ +transport->push(201, [ + 'id' => 'cs_1', + 'status' => 'pending', + 'external_user_id' => 'user-42', + 'platforms' => ['linkedin'], + 'redirect_url' => 'https://yourbrand.com/connected', + 'branding' => ['name' => 'Your Brand', 'logo_url' => null], + 'account_id' => null, + 'url' => 'https://app.fopost.com/connect/cs_1', + 'expires_at' => '2026-03-01T10:00:00Z', + 'used_at' => null, + 'created_at' => '2026-03-01T09:00:00Z', + ]); + $this->transport->push(200, [ + 'id' => 'cs_1', + 'status' => 'used', + 'external_user_id' => 'user-42', + 'platforms' => ['linkedin'], + 'account_id' => 'a_1', + 'expires_at' => '2026-03-01T10:00:00Z', + 'used_at' => '2026-03-01T09:30:00Z', + 'created_at' => '2026-03-01T09:00:00Z', + ]); + + $session = $this->client()->connectSessions()->create( + 'user-42', + ['linkedin'], + workspaceId: 'w_1', + redirectUrl: 'https://yourbrand.com/connected', + branding: ['name' => 'Your Brand'], + ); + $used = $this->client()->connectSessions()->get('cs_1'); + + $this->assertSame('POST', $this->transport->requests[0]['method']); + $this->assertSame('https://api.fopost.com/v1/connect-sessions', $this->transport->requests[0]['url']); + $this->assertSame([ + 'workspaceId' => 'w_1', + 'externalUserId' => 'user-42', + 'platforms' => ['linkedin'], + 'redirectUrl' => 'https://yourbrand.com/connected', + 'branding' => ['name' => 'Your Brand'], + ], json_decode((string) $this->transport->requests[0]['body'], true)); + $this->assertSame('https://app.fopost.com/connect/cs_1', $session->url); + $this->assertSame('pending', $session->status); + $this->assertSame(['linkedin'], $session->platforms); + + $this->assertSame('GET', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/connect-sessions/cs_1', $this->transport->last()['url']); + $this->assertSame('used', $used->status); + $this->assertSame('a_1', $used->accountId); + $this->assertNull($used->url); + } +} From 19ec71c754fe53bca8b602d9ba2ba30db1bc6057 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:44:35 +0200 Subject: [PATCH 04/14] feat(webhooks): endpoints, test sends and the delivery log --- src/Client.php | 9 +++ src/Model/Webhook.php | 53 +++++++++++++ src/Model/WebhookDelivery.php | 57 ++++++++++++++ src/Resource/WebhooksResource.php | 127 ++++++++++++++++++++++++++++++ tests/WebhooksResourceTest.php | 113 ++++++++++++++++++++++++++ 5 files changed, 359 insertions(+) create mode 100644 src/Model/Webhook.php create mode 100644 src/Model/WebhookDelivery.php create mode 100644 src/Resource/WebhooksResource.php create mode 100644 tests/WebhooksResourceTest.php diff --git a/src/Client.php b/src/Client.php index eb2d225..26fdc2c 100644 --- a/src/Client.php +++ b/src/Client.php @@ -26,6 +26,7 @@ use Fopost\Sdk\Resource\QueueResource; use Fopost\Sdk\Resource\SequencesResource; use Fopost\Sdk\Resource\ValidateResource; +use Fopost\Sdk\Resource\WebhooksResource; use Fopost\Sdk\Resource\WhatsappResource; use Fopost\Sdk\Resource\WorkspacesResource; use InvalidArgumentException; @@ -66,6 +67,7 @@ final class Client private readonly BlogsResource $blogs; private readonly MediaResource $media; private readonly ValidateResource $validate; + private readonly WebhooksResource $webhooks; private readonly WhatsappResource $whatsapp; private readonly AnalyticsResource $analytics; private readonly GoogleBusinessResource $googleBusiness; @@ -105,6 +107,7 @@ public function __construct( $this->blogs = new BlogsResource($this->http); $this->media = new MediaResource($this->http); $this->validate = new ValidateResource($this->http); + $this->webhooks = new WebhooksResource($this->http); $this->whatsapp = new WhatsappResource($this->http); $this->analytics = new AnalyticsResource($this->http); $this->googleBusiness = new GoogleBusinessResource($this->http); @@ -203,6 +206,12 @@ public function validate(): ValidateResource return $this->validate; } + /** The endpoints FoPost sends events to, and their delivery log. */ + public function webhooks(): WebhooksResource + { + return $this->webhooks; + } + public function analytics(): AnalyticsResource { return $this->analytics; diff --git a/src/Model/Webhook.php b/src/Model/Webhook.php new file mode 100644 index 0000000..077b98b --- /dev/null +++ b/src/Model/Webhook.php @@ -0,0 +1,53 @@ + $events + * @param array $headerNames Custom header names; the values are write-only. + */ + private function __construct( + array $raw, + public readonly string $id, + public readonly ?string $workspaceId, + public readonly ?string $name, + public readonly string $url, + public readonly array $events, + public readonly array $headerNames, + public readonly bool $active, + /** The signing secret. Present on creation and on a rotation, and only then. */ + public readonly ?string $secret, + public readonly ?DateTimeImmutable $lastTriggeredAt, + public readonly int $failureCount, + public readonly ?DateTimeImmutable $createdAt, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'id'), + self::str($data, 'workspace_id'), + self::str($data, 'name'), + self::requiredStr($data, 'url'), + array_values(array_map(strval(...), self::seq($data, 'events'))), + array_values(array_map(strval(...), self::seq($data, 'header_names'))), + self::bool($data, 'active') ?? false, + self::str($data, 'secret'), + self::date($data, 'last_triggered_at'), + self::int($data, 'failure_count') ?? 0, + self::date($data, 'created_at'), + ); + } +} diff --git a/src/Model/WebhookDelivery.php b/src/Model/WebhookDelivery.php new file mode 100644 index 0000000..4c89c6e --- /dev/null +++ b/src/Model/WebhookDelivery.php @@ -0,0 +1,57 @@ +|null $payload The body exactly as it was sent; only on the single read. */ + private function __construct( + array $raw, + public readonly string $id, + public readonly string $webhookId, + public readonly string $event, + /** The X-FoPost-Delivery id; every attempt of one event shares it. */ + public readonly string $deliveryKey, + /** 1 for the first send; retries and redeliveries count up. */ + public readonly int $attempt, + /** success or failed. */ + public readonly string $status, + /** Null when no response arrived. */ + public readonly ?int $responseStatus, + public readonly ?string $responseSnippet, + public readonly int $durationMs, + public readonly ?string $payloadHash, + public readonly ?DateTimeImmutable $nextRetryAt, + public readonly ?DateTimeImmutable $createdAt, + public readonly ?array $payload, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'id'), + self::requiredStr($data, 'webhook_id'), + self::requiredStr($data, 'event'), + self::requiredStr($data, 'delivery_key'), + self::int($data, 'attempt') ?? 1, + self::requiredStr($data, 'status'), + self::int($data, 'response_status'), + self::str($data, 'response_snippet'), + self::int($data, 'duration_ms') ?? 0, + self::str($data, 'payload_hash'), + self::date($data, 'next_retry_at'), + self::date($data, 'created_at'), + self::nested($data, 'payload'), + ); + } +} diff --git a/src/Resource/WebhooksResource.php b/src/Resource/WebhooksResource.php new file mode 100644 index 0000000..ad252c0 --- /dev/null +++ b/src/Resource/WebhooksResource.php @@ -0,0 +1,127 @@ +webhooks(): the endpoints FoPost sends events to, and their delivery log. + * + * Verify what arrives with `Fopost\Sdk\Webhooks::verify()`. Bodies are camelCase. Needs the `webhooks` scope. + */ +final class WebhooksResource extends Resource +{ + /** @return array */ + public function list(): array + { + return Webhook::listFrom(self::unwrap($this->http->get('/webhooks'))); + } + + /** + * The signing secret comes back once, on `->secret`; omit `$secret` to have one generated. + * + * @param array $events + * @param array|null $headers Sent with every delivery; values are never returned. + */ + public function create( + string $workspaceId, + string $url, + array $events, + ?string $name = null, + ?string $secret = null, + ?array $headers = null, + ): Webhook { + $body = self::compact([ + 'workspaceId' => $workspaceId, + 'url' => $url, + 'events' => array_values($events), + 'name' => $name, + 'secret' => $secret, + 'headers' => $headers, + ]); + + return Webhook::fromArray(self::unwrap($this->http->post('/webhooks', $body))); + } + + /** + * Partial update: only the fields you pass are sent. Passing `$secret` rotates it and + * returns the new value once. `$headers` replaces the header set; a null value keeps an + * existing header's stored value, and null for the whole set clears every header. + * + * @param array|Undefined $events + * @param array|null|Undefined $headers + */ + public function update( + string $webhookId, + string|null|Undefined $name = Undefined::Value, + string|Undefined $url = Undefined::Value, + array|Undefined $events = Undefined::Value, + bool|Undefined $active = Undefined::Value, + string|Undefined $secret = Undefined::Value, + array|null|Undefined $headers = Undefined::Value, + ): Webhook { + $body = []; + if (!Undefined::is($name)) { + $body['name'] = $name; + } + if (!Undefined::is($url)) { + $body['url'] = $url; + } + if (!Undefined::is($events)) { + /** @var array $events */ + $body['events'] = array_values($events); + } + if (!Undefined::is($active)) { + $body['active'] = $active; + } + if (!Undefined::is($secret)) { + $body['secret'] = $secret; + } + if (!Undefined::is($headers)) { + $body['headers'] = $headers; + } + + return Webhook::fromArray(self::unwrap($this->http->put("/webhooks/{$webhookId}", $body))); + } + + public function delete(string $webhookId): void + { + $this->http->delete("/webhooks/{$webhookId}"); + } + + /** Send a test event to the endpoint now. */ + public function test(string $webhookId): void + { + $this->http->post("/webhooks/{$webhookId}/test"); + } + + /** + * Recent delivery attempts, newest first. `$status` is success or failed. + * + * @return array + */ + public function listDeliveries(string $webhookId, ?string $status = null, ?int $limit = null): array + { + $query = self::compact(['status' => $status, 'limit' => $limit]); + + return WebhookDelivery::listFrom(self::unwrap($this->http->get("/webhooks/{$webhookId}/deliveries", $query))); + } + + /** One attempt, with the body exactly as it was sent on `->payload`. */ + public function getDelivery(string $webhookId, string $deliveryId): WebhookDelivery + { + return WebhookDelivery::fromArray( + self::unwrap($this->http->get("/webhooks/{$webhookId}/deliveries/{$deliveryId}")), + ); + } + + /** Send that attempt's body again as a new attempt. A delivery already queued for retry answers 409. */ + public function redeliver(string $webhookId, string $deliveryId): void + { + $this->http->post("/webhooks/{$webhookId}/deliveries/{$deliveryId}/redeliver"); + } +} diff --git a/tests/WebhooksResourceTest.php b/tests/WebhooksResourceTest.php new file mode 100644 index 0000000..115ae87 --- /dev/null +++ b/tests/WebhooksResourceTest.php @@ -0,0 +1,113 @@ + 'wh_1', + 'workspace_id' => 'w_1', + 'name' => 'Orders', + 'url' => 'https://yourbrand.com/hooks/fopost', + 'events' => ['post.published'], + 'header_names' => ['X-Token'], + 'active' => true, + 'last_triggered_at' => null, + 'failure_count' => 0, + 'created_at' => '2026-03-01T09:00:00Z', + ]; + $this->transport->push(200, ['data' => [$hook]]); + $this->transport->push(201, $hook + ['secret' => 'whsec_once']); + $this->transport->push(200, ['active' => false] + $hook); + $this->transport->push(204); + $this->transport->push(204); + + $webhooks = $this->client()->webhooks(); + $list = $webhooks->list(); + $created = $webhooks->create( + 'w_1', + 'https://yourbrand.com/hooks/fopost', + ['post.published'], + name: 'Orders', + headers: ['X-Token' => 'abc'], + ); + $updated = $webhooks->update('wh_1', active: false, headers: null); + $webhooks->test('wh_1'); + $webhooks->delete('wh_1'); + + $this->assertSame('https://api.fopost.com/v1/webhooks', $this->transport->requests[0]['url']); + $this->assertSame(['X-Token'], $list[0]->headerNames); + $this->assertNull($list[0]->secret); + + $this->assertSame('POST', $this->transport->requests[1]['method']); + $this->assertSame([ + 'workspaceId' => 'w_1', + 'url' => 'https://yourbrand.com/hooks/fopost', + 'events' => ['post.published'], + 'name' => 'Orders', + 'headers' => ['X-Token' => 'abc'], + ], json_decode((string) $this->transport->requests[1]['body'], true)); + $this->assertSame('whsec_once', $created->secret); + + $this->assertSame('PUT', $this->transport->requests[2]['method']); + $this->assertSame('https://api.fopost.com/v1/webhooks/wh_1', $this->transport->requests[2]['url']); + $this->assertSame( + ['active' => false, 'headers' => null], + json_decode((string) $this->transport->requests[2]['body'], true), + ); + $this->assertFalse($updated->active); + + $this->assertSame('POST', $this->transport->requests[3]['method']); + $this->assertSame('https://api.fopost.com/v1/webhooks/wh_1/test', $this->transport->requests[3]['url']); + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/webhooks/wh_1', $this->transport->last()['url']); + } + + public function testDeliveriesAreListedReadAndRedelivered(): void + { + $delivery = [ + 'id' => 'd_1', + 'webhook_id' => 'wh_1', + 'event' => 'post.published', + 'delivery_key' => 'dk_1', + 'attempt' => 2, + 'status' => 'failed', + 'response_status' => 500, + 'response_snippet' => 'boom', + 'duration_ms' => 120, + 'payload_hash' => 'abc', + 'next_retry_at' => '2026-03-01T09:10:00Z', + 'created_at' => '2026-03-01T09:00:00Z', + ]; + $this->transport->push(200, ['data' => [$delivery]]); + $this->transport->push(200, $delivery + ['payload' => ['event' => 'post.published']]); + $this->transport->push(204); + + $webhooks = $this->client()->webhooks(); + $list = $webhooks->listDeliveries('wh_1', status: 'failed', limit: 10); + $one = $webhooks->getDelivery('wh_1', 'd_1'); + $webhooks->redeliver('wh_1', 'd_1'); + + $this->assertSame( + 'https://api.fopost.com/v1/webhooks/wh_1/deliveries?status=failed&limit=10', + $this->transport->requests[0]['url'], + ); + $this->assertSame(2, $list[0]->attempt); + $this->assertSame(500, $list[0]->responseStatus); + $this->assertNull($list[0]->payload); + + $this->assertSame('https://api.fopost.com/v1/webhooks/wh_1/deliveries/d_1', $this->transport->requests[1]['url']); + $this->assertSame(['event' => 'post.published'], $one->payload); + $this->assertSame('2026-03-01T09:10:00+00:00', $one->nextRetryAt?->format(DATE_ATOM)); + + $this->assertSame('POST', $this->transport->last()['method']); + $this->assertSame( + 'https://api.fopost.com/v1/webhooks/wh_1/deliveries/d_1/redeliver', + $this->transport->last()['url'], + ); + } +} From 46824c3d984ed300cb26a91b878624ae9a600ac4 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:44:44 +0200 Subject: [PATCH 05/14] style(tests): wrap a long webhook assertion --- tests/WebhooksResourceTest.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/WebhooksResourceTest.php b/tests/WebhooksResourceTest.php index 115ae87..b169123 100644 --- a/tests/WebhooksResourceTest.php +++ b/tests/WebhooksResourceTest.php @@ -100,7 +100,10 @@ public function testDeliveriesAreListedReadAndRedelivered(): void $this->assertSame(500, $list[0]->responseStatus); $this->assertNull($list[0]->payload); - $this->assertSame('https://api.fopost.com/v1/webhooks/wh_1/deliveries/d_1', $this->transport->requests[1]['url']); + $this->assertSame( + 'https://api.fopost.com/v1/webhooks/wh_1/deliveries/d_1', + $this->transport->requests[1]['url'], + ); $this->assertSame(['event' => 'post.published'], $one->payload); $this->assertSame('2026-03-01T09:10:00+00:00', $one->nextRetryAt?->format(DATE_ATOM)); From ba28a92e88fd0e2e99b0bf294dfacef7b2788252 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:46:44 +0200 Subject: [PATCH 06/14] feat(automations): automations, stats, versions and runs --- src/Client.php | 9 ++ src/Model/Automation.php | 74 +++++++++++ src/Model/AutomationNodeRef.php | 30 +++++ src/Model/AutomationRestore.php | 34 +++++ src/Model/AutomationRun.php | 72 +++++++++++ src/Model/AutomationRunLog.php | 53 ++++++++ src/Model/AutomationStats.php | 39 ++++++ src/Model/AutomationStep.php | 33 +++++ src/Model/AutomationToggle.php | 21 ++++ src/Model/AutomationVersion.php | 48 +++++++ src/Resource/AutomationsResource.php | 181 +++++++++++++++++++++++++++ tests/AutomationsTest.php | 179 ++++++++++++++++++++++++++ 12 files changed, 773 insertions(+) create mode 100644 src/Model/Automation.php create mode 100644 src/Model/AutomationNodeRef.php create mode 100644 src/Model/AutomationRestore.php create mode 100644 src/Model/AutomationRun.php create mode 100644 src/Model/AutomationRunLog.php create mode 100644 src/Model/AutomationStats.php create mode 100644 src/Model/AutomationStep.php create mode 100644 src/Model/AutomationToggle.php create mode 100644 src/Model/AutomationVersion.php create mode 100644 src/Resource/AutomationsResource.php create mode 100644 tests/AutomationsTest.php diff --git a/src/Client.php b/src/Client.php index 26fdc2c..b881604 100644 --- a/src/Client.php +++ b/src/Client.php @@ -11,6 +11,7 @@ use Fopost\Sdk\Resource\AdsResource; use Fopost\Sdk\Resource\AnalyticsResource; use Fopost\Sdk\Resource\AiResource; +use Fopost\Sdk\Resource\AutomationsResource; use Fopost\Sdk\Resource\BlogResource; use Fopost\Sdk\Resource\BroadcastsResource; use Fopost\Sdk\Resource\ConnectSessionsResource; @@ -56,6 +57,7 @@ final class Client private readonly LabelsResource $labels; private readonly ActivityResource $activity; private readonly AiResource $ai; + private readonly AutomationsResource $automations; private readonly InboxResource $inbox; private readonly ContactsResource $contacts; private readonly BroadcastsResource $broadcasts; @@ -97,6 +99,7 @@ public function __construct( $this->labels = new LabelsResource($this->http); $this->activity = new ActivityResource($this->http); $this->ai = new AiResource($this->http); + $this->automations = new AutomationsResource($this->http); $this->inbox = new InboxResource($this->http); $this->contacts = new ContactsResource($this->http); $this->broadcasts = new BroadcastsResource($this->http); @@ -155,6 +158,12 @@ public function ai(): AiResource return $this->ai; } + /** Triggers and the step chains they run. */ + public function automations(): AutomationsResource + { + return $this->automations; + } + public function knowledge(): KnowledgeResource { return $this->knowledge; diff --git a/src/Model/Automation.php b/src/Model/Automation.php new file mode 100644 index 0000000..93f27dc --- /dev/null +++ b/src/Model/Automation.php @@ -0,0 +1,74 @@ + $triggerConfig + * @param array{days: array, start: string, end: string}|null $scheduleWindow + * @param array|null $maxPerDay + * @param array{nodes: array>, edges: array>}|null $graph + * @param array $steps + */ + private function __construct( + array $raw, + public readonly string $id, + public readonly ?string $workspaceId, + public readonly string $name, + public readonly ?string $description, + public readonly string $triggerType, + public readonly array $triggerConfig, + public readonly bool $active, + /** Wall-clock window (workspace timezone) runs may act in; null is unrestricted. */ + public readonly ?array $scheduleWindow, + /** Daily caps; null is unrestricted. */ + public readonly ?array $maxPerDay, + /** Max AI credits one unattended run may spend. */ + public readonly ?int $creditCeiling, + /** Generated posts go through the approval queue. */ + public readonly bool $approvalMode, + /** The webhook trigger secret. Returned on creation only. */ + public readonly ?string $secret, + public readonly ?array $graph, + public readonly array $steps, + public readonly ?DateTimeImmutable $lastTriggeredAt, + public readonly int $runCount, + public readonly ?DateTimeImmutable $createdAt, + public readonly ?DateTimeImmutable $updatedAt, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'id'), + self::str($data, 'workspace_id'), + self::requiredStr($data, 'name'), + self::str($data, 'description'), + self::requiredStr($data, 'trigger_type'), + self::map($data, 'trigger_config'), + self::bool($data, 'active') ?? false, + self::nested($data, 'schedule_window'), + self::nested($data, 'max_per_day'), + self::int($data, 'credit_ceiling'), + self::bool($data, 'approval_mode') ?? false, + self::str($data, 'secret'), + self::nested($data, 'graph'), + AutomationStep::listFrom(self::seq($data, 'steps')), + self::date($data, 'last_triggered_at'), + self::int($data, 'run_count') ?? 0, + self::date($data, 'created_at'), + self::date($data, 'updated_at'), + ); + } +} diff --git a/src/Model/AutomationNodeRef.php b/src/Model/AutomationNodeRef.php new file mode 100644 index 0000000..af4c165 --- /dev/null +++ b/src/Model/AutomationNodeRef.php @@ -0,0 +1,30 @@ +>, edges: array>}|null $graph + * @param array $steps + */ + private function __construct( + array $raw, + public readonly int $version, + public readonly ?array $graph, + public readonly array $steps, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'version') ?? 0, + self::nested($data, 'graph'), + AutomationStep::listFrom(self::seq($data, 'steps')), + ); + } +} diff --git a/src/Model/AutomationRun.php b/src/Model/AutomationRun.php new file mode 100644 index 0000000..1865580 --- /dev/null +++ b/src/Model/AutomationRun.php @@ -0,0 +1,72 @@ +|null $triggerEvent + * @param array|null $context + * @param array|null $initialContext + * @param array $logs + */ + private function __construct( + array $raw, + public readonly int $id, + public readonly ?string $automationId, + /** running, deferred, waiting, completed, failed or cancelled. */ + public readonly string $status, + public readonly ?int $currentStep, + public readonly ?string $currentNodeId, + /** When a waiting run gives up on the reply. */ + public readonly ?DateTimeImmutable $waitingUntil, + public readonly ?array $triggerEvent, + public readonly ?array $context, + /** The context before the first step; what a replay re-runs against. */ + public readonly ?array $initialContext, + public readonly ?int $replayOfRunId, + public readonly ?DateTimeImmutable $deferredUntil, + /** `outside_window` or `daily_cap`. */ + public readonly ?string $deferReason, + public readonly ?string $deferDetail, + public readonly int $deferCount, + public readonly ?DateTimeImmutable $startedAt, + public readonly ?DateTimeImmutable $completedAt, + public readonly ?string $errorMessage, + public readonly array $logs, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'id') ?? 0, + self::str($data, 'automation_id'), + self::requiredStr($data, 'status'), + self::int($data, 'current_step'), + self::str($data, 'current_node_id'), + self::date($data, 'waiting_until'), + self::nested($data, 'trigger_event'), + self::nested($data, 'context'), + self::nested($data, 'initial_context'), + self::int($data, 'replay_of_run_id'), + self::date($data, 'deferred_until'), + self::str($data, 'defer_reason'), + self::str($data, 'defer_detail'), + self::int($data, 'defer_count') ?? 0, + self::date($data, 'started_at'), + self::date($data, 'completed_at'), + self::str($data, 'error_message'), + AutomationRunLog::listFrom(self::seq($data, 'logs')), + ); + } +} diff --git a/src/Model/AutomationRunLog.php b/src/Model/AutomationRunLog.php new file mode 100644 index 0000000..2df8e1e --- /dev/null +++ b/src/Model/AutomationRunLog.php @@ -0,0 +1,53 @@ +|null $inputSnapshot + * @param array|null $outputSnapshot + */ + private function __construct( + array $raw, + public readonly int $id, + public readonly int $stepPosition, + public readonly ?string $nodeId, + /** The output the run left the node through. */ + public readonly ?string $handle, + public readonly string $status, + public readonly ?array $inputSnapshot, + public readonly ?array $outputSnapshot, + public readonly ?DateTimeImmutable $startedAt, + public readonly ?DateTimeImmutable $completedAt, + public readonly ?int $durationMs, + public readonly ?string $errorMessage, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'id') ?? 0, + self::int($data, 'step_position') ?? 0, + self::str($data, 'node_id'), + self::str($data, 'handle'), + self::requiredStr($data, 'status'), + self::nested($data, 'input_snapshot'), + self::nested($data, 'output_snapshot'), + self::date($data, 'started_at'), + self::date($data, 'completed_at'), + self::int($data, 'duration_ms'), + self::str($data, 'error_message'), + ); + } +} diff --git a/src/Model/AutomationStats.php b/src/Model/AutomationStats.php new file mode 100644 index 0000000..5d20fdb --- /dev/null +++ b/src/Model/AutomationStats.php @@ -0,0 +1,39 @@ + $runsByStatus + * @param array $recentRuns + */ + private function __construct( + array $raw, + public readonly int $totalAutomations, + public readonly int $activeAutomations, + /** Runs started in the last 24 hours. */ + public readonly int $totalRuns24h, + public readonly array $runsByStatus, + public readonly array $recentRuns, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'total_automations') ?? 0, + self::int($data, 'active_automations') ?? 0, + self::int($data, 'total_runs_24h') ?? 0, + array_map(intval(...), self::map($data, 'runs_by_status')), + AutomationRun::listFrom(self::seq($data, 'recent_runs')), + ); + } +} diff --git a/src/Model/AutomationStep.php b/src/Model/AutomationStep.php new file mode 100644 index 0000000..a053d71 --- /dev/null +++ b/src/Model/AutomationStep.php @@ -0,0 +1,33 @@ + $actionConfig */ + private function __construct( + array $raw, + public readonly int $position, + public readonly ?string $nodeId, + public readonly string $actionType, + public readonly array $actionConfig, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'position') ?? 0, + self::str($data, 'node_id'), + self::requiredStr($data, 'action_type'), + self::map($data, 'action_config'), + ); + } +} diff --git a/src/Model/AutomationToggle.php b/src/Model/AutomationToggle.php new file mode 100644 index 0000000..db10593 --- /dev/null +++ b/src/Model/AutomationToggle.php @@ -0,0 +1,21 @@ + $nodesAdded + * @param array $nodesRemoved + * @param array{nodes: array>, edges: array>}|null $graph + */ + private function __construct( + array $raw, + public readonly int $version, + public readonly ?string $note, + public readonly ?string $createdByName, + public readonly ?DateTimeImmutable $createdAt, + public readonly ?int $nodeCount, + public readonly array $nodesAdded, + public readonly array $nodesRemoved, + public readonly ?array $graph, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $createdBy = self::nested($data, 'created_by') ?? []; + + return new self( + $data, + self::int($data, 'version') ?? 0, + self::str($data, 'note'), + self::str($createdBy, 'name'), + self::date($data, 'created_at'), + self::int($data, 'node_count'), + AutomationNodeRef::listFrom(self::seq($data, 'nodes_added')), + AutomationNodeRef::listFrom(self::seq($data, 'nodes_removed')), + self::nested($data, 'graph'), + ); + } +} diff --git a/src/Resource/AutomationsResource.php b/src/Resource/AutomationsResource.php new file mode 100644 index 0000000..0cbbb6a --- /dev/null +++ b/src/Resource/AutomationsResource.php @@ -0,0 +1,181 @@ +automations(): triggers and the step chains they run. + * + * Request bodies are camelCase. Needs the `automations` scope. The webhook + * trigger endpoint is not here: it is called with the automation's own + * secret, not an API key. + */ +final class AutomationsResource extends Resource +{ + /** @return array */ + public function list(): array + { + return Automation::listFrom(self::unwrap($this->http->get('/automations'))); + } + + public function stats(): AutomationStats + { + return AutomationStats::fromArray(self::unwrap($this->http->get('/automations/stats'))); + } + + public function get(string $automationId): Automation + { + return Automation::fromArray(self::unwrap($this->http->get("/automations/{$automationId}"))); + } + + /** + * Give `$steps` as an ordered list of `{actionType, actionConfig}` or `$graph` as + * `{nodes, edges}`; the graph wins when both are given. A webhook trigger's secret + * comes back once on `->secret`. + * + * @param array $triggerConfig + * @param array>|null $steps + * @param array{nodes: array>, edges: array>}|null $graph + * @param array $extra + */ + public function create( + string $workspaceId, + string $name, + string $triggerType, + array $triggerConfig = [], + ?array $steps = null, + ?array $graph = null, + ?string $description = null, + ?bool $active = null, + array $extra = [], + ): Automation { + $body = [ + 'workspaceId' => $workspaceId, + 'name' => $name, + 'triggerType' => $triggerType, + 'triggerConfig' => (object) $triggerConfig, + ] + self::compact([ + 'steps' => $steps !== null ? array_values($steps) : null, + 'graph' => $graph, + 'description' => $description, + 'active' => $active, + ]) + $extra; + + return Automation::fromArray(self::unwrap($this->http->post('/automations', $body))); + } + + /** + * Partial update: only the fields you pass are sent. A new `$steps` or `$graph` saves a version. + * + * @param array|Undefined $triggerConfig + * @param array>|Undefined $steps + * @param array|Undefined $graph + * @param array $extra + */ + public function update( + string $automationId, + string|Undefined $name = Undefined::Value, + string|null|Undefined $description = Undefined::Value, + string|Undefined $triggerType = Undefined::Value, + array|Undefined $triggerConfig = Undefined::Value, + array|Undefined $steps = Undefined::Value, + array|Undefined $graph = Undefined::Value, + bool|Undefined $active = Undefined::Value, + array $extra = [], + ): Automation { + $body = []; + if (!Undefined::is($name)) { + $body['name'] = $name; + } + if (!Undefined::is($description)) { + $body['description'] = $description; + } + if (!Undefined::is($triggerType)) { + $body['triggerType'] = $triggerType; + } + if (!Undefined::is($triggerConfig)) { + /** @var array $triggerConfig */ + $body['triggerConfig'] = (object) $triggerConfig; + } + if (!Undefined::is($steps)) { + /** @var array> $steps */ + $body['steps'] = array_values($steps); + } + if (!Undefined::is($graph)) { + $body['graph'] = $graph; + } + if (!Undefined::is($active)) { + $body['active'] = $active; + } + $body = array_merge($body, $extra); + + return Automation::fromArray(self::unwrap($this->http->put("/automations/{$automationId}", $body))); + } + + public function delete(string $automationId): void + { + $this->http->delete("/automations/{$automationId}"); + } + + /** Flip the automation between active and paused. */ + public function toggle(string $automationId): AutomationToggle + { + return AutomationToggle::fromArray(self::unwrap($this->http->post("/automations/{$automationId}/toggle"))); + } + + /** + * Saved versions of the graph, newest first, with what each one added and removed. + * + * @return Page + */ + public function listVersions(string $automationId, int $page = 1, int $perPage = 20): Page + { + $query = ['page' => $page, 'per_page' => $perPage]; + + return self::page(AutomationVersion::class, $this->http->get("/automations/{$automationId}/versions", $query)); + } + + /** One version with its full graph. */ + public function getVersion(string $automationId, int $version): AutomationVersion + { + return AutomationVersion::fromArray( + self::unwrap($this->http->get("/automations/{$automationId}/versions/{$version}")), + ); + } + + /** Make that version's graph current again, as a new version. */ + public function restoreVersion(string $automationId, int $version): AutomationRestore + { + return AutomationRestore::fromArray( + self::unwrap($this->http->post("/automations/{$automationId}/versions/{$version}/restore")), + ); + } + + /** + * Runs of the automation, newest first. + * + * @return Page + */ + public function listRuns(string $automationId, int $page = 1, int $perPage = 20): Page + { + $query = ['page' => $page, 'per_page' => $perPage]; + + return self::page(AutomationRun::class, $this->http->get("/automations/{$automationId}/runs", $query)); + } + + /** One run with its step logs. */ + public function getRun(string $automationId, int $runId): AutomationRun + { + return AutomationRun::fromArray(self::unwrap($this->http->get("/automations/{$automationId}/runs/{$runId}"))); + } +} diff --git a/tests/AutomationsTest.php b/tests/AutomationsTest.php new file mode 100644 index 0000000..db8716c --- /dev/null +++ b/tests/AutomationsTest.php @@ -0,0 +1,179 @@ + 'au_1', + 'workspace_id' => 'w_1', + 'name' => 'Cross-post', + 'description' => null, + 'trigger_type' => 'content_created', + 'trigger_config' => ['accountIds' => ['a_1']], + 'active' => true, + 'schedule_window' => null, + 'max_per_day' => ['posts' => 5], + 'credit_ceiling' => 50, + 'approval_mode' => false, + 'steps' => [['position' => 0, 'node_id' => 'n1', 'action_type' => 'publish', 'action_config' => []]], + 'run_count' => 3, + 'created_at' => '2026-03-01T09:00:00Z', + 'updated_at' => '2026-03-01T09:00:00Z', + ]; + $this->transport->push(200, ['data' => [$automation]]); + $this->transport->push(200, [ + 'total_automations' => 1, + 'active_automations' => 1, + 'total_runs_24h' => 2, + 'runs_by_status' => ['completed' => 2], + 'recent_runs' => [['id' => 7, 'automation_id' => 'au_1', 'status' => 'completed']], + ]); + $this->transport->push(201, $automation + ['secret' => 'as_once']); + $this->transport->push(200, $automation); + $this->transport->push(200, ['id' => 'au_1', 'active' => false]); + $this->transport->push(204); + + $automations = $this->client()->automations(); + $list = $automations->list(); + $stats = $automations->stats(); + $created = $automations->create( + 'w_1', + 'Cross-post', + 'content_created', + ['accountIds' => ['a_1']], + steps: [['actionType' => 'publish', 'actionConfig' => ['accountIds' => ['a_2']]]], + ); + $updated = $automations->update('au_1', name: 'Cross-post v2', active: false); + $toggled = $automations->toggle('au_1'); + $automations->delete('au_1'); + + $this->assertSame('https://api.fopost.com/v1/automations', $this->transport->requests[0]['url']); + $this->assertSame('publish', $list[0]->steps[0]->actionType); + $this->assertSame(['posts' => 5], $list[0]->maxPerDay); + $this->assertSame(50, $list[0]->creditCeiling); + + $this->assertSame('https://api.fopost.com/v1/automations/stats', $this->transport->requests[1]['url']); + $this->assertSame(['completed' => 2], $stats->runsByStatus); + $this->assertSame(7, $stats->recentRuns[0]->id); + + $this->assertSame('POST', $this->transport->requests[2]['method']); + $this->assertSame([ + 'workspaceId' => 'w_1', + 'name' => 'Cross-post', + 'triggerType' => 'content_created', + 'triggerConfig' => ['accountIds' => ['a_1']], + 'steps' => [['actionType' => 'publish', 'actionConfig' => ['accountIds' => ['a_2']]]], + ], json_decode((string) $this->transport->requests[2]['body'], true)); + $this->assertSame('as_once', $created->secret); + + $this->assertSame('PUT', $this->transport->requests[3]['method']); + $this->assertSame('https://api.fopost.com/v1/automations/au_1', $this->transport->requests[3]['url']); + $this->assertSame( + ['name' => 'Cross-post v2', 'active' => false], + json_decode((string) $this->transport->requests[3]['body'], true), + ); + $this->assertSame('au_1', $updated->id); + + $this->assertSame('https://api.fopost.com/v1/automations/au_1/toggle', $this->transport->requests[4]['url']); + $this->assertFalse($toggled->active); + + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/automations/au_1', $this->transport->last()['url']); + } + + public function testAnEmptyTriggerConfigIsSentAsAnObject(): void + { + $this->transport->push(201, ['id' => 'au_1', 'name' => 'Daily', 'trigger_type' => 'schedule']); + + $this->client()->automations()->create('w_1', 'Daily', 'schedule'); + + $this->assertStringContainsString('"triggerConfig":{}', (string) $this->transport->last()['body']); + } + + public function testVersionsAreListedReadAndRestored(): void + { + $this->transport->push(200, [ + 'data' => [[ + 'version' => 3, + 'note' => 'Added a delay', + 'created_by' => ['name' => 'Ops'], + 'created_at' => '2026-03-01T09:00:00Z', + 'node_count' => 4, + 'nodes_added' => [['id' => 'n4', 'kind' => 'delay', 'label' => null]], + 'nodes_removed' => [], + ]], + 'meta' => ['page' => 1, 'per_page' => 20, 'total' => 3, 'total_pages' => 1], + ]); + $this->transport->push(200, [ + 'version' => 2, + 'note' => null, + 'created_by' => null, + 'created_at' => '2026-02-01T09:00:00Z', + 'graph' => ['nodes' => [['id' => 'n1', 'kind' => 'trigger']], 'edges' => []], + ]); + $this->transport->push(200, [ + 'version' => 4, + 'graph' => ['nodes' => [['id' => 'n1', 'kind' => 'trigger']], 'edges' => []], + 'steps' => [], + ]); + + $automations = $this->client()->automations(); + $page = $automations->listVersions('au_1', 1, 20); + $version = $automations->getVersion('au_1', 2); + $restored = $automations->restoreVersion('au_1', 2); + + $this->assertSame( + 'https://api.fopost.com/v1/automations/au_1/versions?page=1&per_page=20', + $this->transport->requests[0]['url'], + ); + $this->assertSame(3, $page->meta->total); + $this->assertSame('Ops', $page->items[0]->createdByName); + $this->assertSame('delay', $page->items[0]->nodesAdded[0]->kind); + $this->assertNull($page->items[0]->graph); + + $this->assertSame( + 'https://api.fopost.com/v1/automations/au_1/versions/2', + $this->transport->requests[1]['url'], + ); + $this->assertSame('n1', $version->graph['nodes'][0]['id']); + $this->assertNull($version->createdByName); + + $this->assertSame('POST', $this->transport->last()['method']); + $this->assertSame( + 'https://api.fopost.com/v1/automations/au_1/versions/2/restore', + $this->transport->last()['url'], + ); + $this->assertSame(4, $restored->version); + } + + public function testRunsAreListedAndRead(): void + { + $this->transport->push(200, [ + 'data' => [['id' => 9, 'status' => 'deferred', 'defer_reason' => 'daily_cap', 'defer_count' => 1]], + 'meta' => ['page' => 1, 'per_page' => 20, 'total' => 1, 'total_pages' => 1], + ]); + $this->transport->push(200, [ + 'id' => 9, + 'automation_id' => 'au_1', + 'status' => 'completed', + 'started_at' => '2026-03-01T09:00:00Z', + 'logs' => [['id' => 1, 'step_position' => 0, 'status' => 'completed', 'duration_ms' => 12]], + ]); + + $runs = $this->client()->automations()->listRuns('au_1'); + $run = $this->client()->automations()->getRun('au_1', 9); + + $this->assertSame( + 'https://api.fopost.com/v1/automations/au_1/runs?page=1&per_page=20', + $this->transport->requests[0]['url'], + ); + $this->assertSame('daily_cap', $runs->items[0]->deferReason); + $this->assertSame('https://api.fopost.com/v1/automations/au_1/runs/9', $this->transport->last()['url']); + $this->assertSame(12, $run->logs[0]->durationMs); + } +} From 3fa71109ef5fb8e39d7a02e7307d7b8e1674731d Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:48:23 +0200 Subject: [PATCH 07/14] feat(workspaces): create, update and delete --- src/Model/Workspace.php | 9 +++- src/Resource/WorkspacesResource.php | 76 +++++++++++++++++++++++++++++ tests/WorkspacesTest.php | 36 ++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/src/Model/Workspace.php b/src/Model/Workspace.php index 2d45523..a3d8240 100644 --- a/src/Model/Workspace.php +++ b/src/Model/Workspace.php @@ -9,7 +9,10 @@ /** A workspace the API key can reach. */ final class Workspace extends Model { - /** @param array $accounts */ + /** + * @param array $connectRedirectDomains Hostnames a hosted connect session may redirect to. + * @param array $accounts + */ private function __construct( array $raw, public readonly string $id, @@ -26,7 +29,9 @@ private function __construct( public readonly ?bool $aiAltTextEnabled, public readonly ?string $brandColor, public readonly ?string $role, + public readonly array $connectRedirectDomains, public readonly ?DateTimeImmutable $createdAt, + public readonly ?DateTimeImmutable $updatedAt, public readonly array $accounts, ) { parent::__construct($raw); @@ -52,7 +57,9 @@ public static function fromArray(mixed $data): static self::bool($data, 'ai_alt_text_enabled'), self::str($data, 'brand_color'), self::str($data, 'role'), + array_values(array_map(strval(...), self::seq($data, 'connect_redirect_domains'))), self::date($data, 'created_at'), + self::date($data, 'updated_at'), SocialAccount::listFrom(self::seq($data, 'accounts')), ); } diff --git a/src/Resource/WorkspacesResource.php b/src/Resource/WorkspacesResource.php index d4ef0cd..7bc7897 100644 --- a/src/Resource/WorkspacesResource.php +++ b/src/Resource/WorkspacesResource.php @@ -5,6 +5,7 @@ namespace Fopost\Sdk\Resource; use Fopost\Sdk\Model\Workspace; +use Fopost\Sdk\Undefined; /** $client->workspaces(): the workspaces the key can reach. */ final class WorkspacesResource extends Resource @@ -19,4 +20,79 @@ public function get(string $workspaceId): Workspace { return Workspace::fromArray(self::unwrap($this->http->get("/workspaces/{$workspaceId}"))); } + + /** `$type` is PERSONAL, TEAM, ORGANIZATION, CLIENT, PROJECT, DEPARTMENT, EVENT, TEMPORARY, COMMUNITY, BRAND or AGENCY. */ + public function create( + string $name, + ?string $type = null, + ?string $timezone = null, + ?string $language = null, + ?string $logo = null, + ?string $website = null, + ?string $country = null, + ?string $description = null, + ): Workspace { + $body = self::compact([ + 'name' => $name, + 'type' => $type, + 'timezone' => $timezone, + 'language' => $language, + 'logo' => $logo, + 'website' => $website, + 'country' => $country, + 'description' => $description, + ]); + + return Workspace::fromArray(self::unwrap($this->http->post('/workspaces', $body))); + } + + /** + * Partial update: only the fields you pass are sent. The settings are camelCase on the wire. + * + * @param array|Undefined $connectRedirectDomains + */ + public function update( + string $workspaceId, + string|Undefined $name = Undefined::Value, + string|Undefined $type = Undefined::Value, + string|Undefined $timezone = Undefined::Value, + string|Undefined $language = Undefined::Value, + string|null|Undefined $logo = Undefined::Value, + string|null|Undefined $website = Undefined::Value, + string|null|Undefined $country = Undefined::Value, + string|null|Undefined $description = Undefined::Value, + bool|Undefined $requireApproval = Undefined::Value, + bool|Undefined $aiAltTextEnabled = Undefined::Value, + string|null|Undefined $brandColor = Undefined::Value, + array|Undefined $connectRedirectDomains = Undefined::Value, + ): Workspace { + $fields = [ + 'name' => $name, + 'type' => $type, + 'timezone' => $timezone, + 'language' => $language, + 'logo' => $logo, + 'website' => $website, + 'country' => $country, + 'description' => $description, + 'requireApproval' => $requireApproval, + 'aiAltTextEnabled' => $aiAltTextEnabled, + 'brandColor' => $brandColor, + 'connectRedirectDomains' => $connectRedirectDomains, + ]; + $body = []; + foreach ($fields as $key => $value) { + if (!Undefined::is($value)) { + $body[$key] = is_array($value) ? array_values($value) : $value; + } + } + + return Workspace::fromArray(self::unwrap($this->http->put("/workspaces/{$workspaceId}", $body))); + } + + /** A workspace with connected accounts answers 409 until they are disconnected or moved. */ + public function delete(string $workspaceId): void + { + $this->http->delete("/workspaces/{$workspaceId}"); + } } diff --git a/tests/WorkspacesTest.php b/tests/WorkspacesTest.php index e6df130..1c48fde 100644 --- a/tests/WorkspacesTest.php +++ b/tests/WorkspacesTest.php @@ -39,4 +39,40 @@ public function testGetReturnsOneWorkspaceWithItsAccounts(): void $this->assertCount(1, $workspace->accounts); $this->assertSame('bluesky', $workspace->accounts[0]->platform); } + + public function testCreateUpdateAndDeleteSendTheRightBodies(): void + { + $this->transport->push(201, ['id' => 'w_2', 'name' => 'Client', 'connect_redirect_domains' => []]); + $this->transport->push(200, [ + 'id' => 'w_2', + 'name' => 'Client', + 'require_approval' => true, + 'connect_redirect_domains' => ['yourbrand.com'], + ]); + $this->transport->push(204); + + $workspaces = $this->client()->workspaces(); + $created = $workspaces->create('Client', type: 'CLIENT', timezone: 'Europe/Zagreb'); + $updated = $workspaces->update('w_2', requireApproval: true, connectRedirectDomains: ['yourbrand.com']); + $workspaces->delete('w_2'); + + $this->assertSame('POST', $this->transport->requests[0]['method']); + $this->assertSame('https://api.fopost.com/v1/workspaces', $this->transport->requests[0]['url']); + $this->assertSame( + ['name' => 'Client', 'type' => 'CLIENT', 'timezone' => 'Europe/Zagreb'], + json_decode((string) $this->transport->requests[0]['body'], true), + ); + $this->assertSame('w_2', $created->id); + + $this->assertSame('PUT', $this->transport->requests[1]['method']); + $this->assertSame('https://api.fopost.com/v1/workspaces/w_2', $this->transport->requests[1]['url']); + $this->assertSame( + ['requireApproval' => true, 'connectRedirectDomains' => ['yourbrand.com']], + json_decode((string) $this->transport->requests[1]['body'], true), + ); + $this->assertSame(['yourbrand.com'], $updated->connectRedirectDomains); + + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/workspaces/w_2', $this->transport->last()['url']); + } } From dc4853a038f34b25662161e8fe9619eacfcb2ef6 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:48:24 +0200 Subject: [PATCH 08/14] feat(accounts): X communities --- src/Model/XCommunity.php | 46 ++++++++++++++++++++++++ src/Model/XCommunityMatch.php | 32 +++++++++++++++++ src/Resource/AccountsResource.php | 52 +++++++++++++++++++++++++++ tests/CommunitiesTest.php | 60 +++++++++++++++++++++++++++++++ 4 files changed, 190 insertions(+) create mode 100644 src/Model/XCommunity.php create mode 100644 src/Model/XCommunityMatch.php create mode 100644 tests/CommunitiesTest.php diff --git a/src/Model/XCommunity.php b/src/Model/XCommunity.php new file mode 100644 index 0000000..441a54e --- /dev/null +++ b/src/Model/XCommunity.php @@ -0,0 +1,46 @@ +http->get("/accounts/{$accountId}/linkedin/mentions", ['q' => $q])), ); } + + // ── X communities ── + + /** + * The X communities linked to the account. + * + * @return array + */ + public function listCommunities(string $accountId): array + { + return XCommunity::listFrom(self::unwrap($this->http->get("/accounts/{$accountId}/communities"))); + } + + /** + * Pull the account's community memberships from X and link them. + * + * @return array + */ + public function syncCommunities(string $accountId): array + { + return XCommunity::listFrom(self::unwrap($this->http->post("/accounts/{$accountId}/communities/sync"))); + } + + /** + * Find communities on X by name. + * + * @return array + */ + public function searchCommunities(string $accountId, string $q): array + { + $body = $this->http->get("/accounts/{$accountId}/communities/search", ['q' => $q]); + + return XCommunityMatch::listFrom(self::unwrap($body)); + } + + /** Link a community by its X id when the sync cannot see it. */ + public function addCommunity(string $accountId, string $communityId, ?string $name = null): XCommunity + { + $body = self::compact(['communityId' => $communityId, 'name' => $name]); + + $result = $this->http->post("/accounts/{$accountId}/communities/manual", $body); + + return XCommunity::fromArray(self::unwrap($result)); + } + + /** `$communityId` is the internal `XCommunity::$id`, not the X id. */ + public function removeCommunity(string $accountId, int $communityId): void + { + $this->http->delete("/accounts/{$accountId}/communities/{$communityId}"); + } } diff --git a/tests/CommunitiesTest.php b/tests/CommunitiesTest.php new file mode 100644 index 0000000..af02f96 --- /dev/null +++ b/tests/CommunitiesTest.php @@ -0,0 +1,60 @@ + 12, + 'account_id' => 'a_1', + 'community_id' => '1700000000000000000', + 'name' => 'PHP Builders', + 'member_count' => 420, + 'description' => null, + 'image_url' => null, + 'last_synced_at' => '2026-03-01T09:00:00Z', + 'created_at' => '2026-03-01T09:00:00Z', + ]; + $this->transport->push(200, ['data' => [$community]]); + $this->transport->push(200, ['data' => [$community], 'note' => 'synced']); + $this->transport->push(200, ['data' => [['id' => '17', 'name' => 'PHP', 'member_count' => 9]]]); + $this->transport->push(201, $community); + $this->transport->push(204); + + $accounts = $this->client()->accounts(); + $list = $accounts->listCommunities('a_1'); + $synced = $accounts->syncCommunities('a_1'); + $matches = $accounts->searchCommunities('a_1', 'PHP'); + $added = $accounts->addCommunity('a_1', '1700000000000000000', 'PHP Builders'); + $accounts->removeCommunity('a_1', 12); + + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/communities', $this->transport->requests[0]['url']); + $this->assertSame(12, $list[0]->id); + $this->assertSame('POST', $this->transport->requests[1]['method']); + $this->assertSame( + 'https://api.fopost.com/v1/accounts/a_1/communities/sync', + $this->transport->requests[1]['url'], + ); + $this->assertSame(420, $synced[0]->memberCount); + $this->assertSame( + 'https://api.fopost.com/v1/accounts/a_1/communities/search?q=PHP', + $this->transport->requests[2]['url'], + ); + $this->assertSame('17', $matches[0]->id); + $this->assertSame( + 'https://api.fopost.com/v1/accounts/a_1/communities/manual', + $this->transport->requests[3]['url'], + ); + $this->assertSame( + ['communityId' => '1700000000000000000', 'name' => 'PHP Builders'], + json_decode((string) $this->transport->requests[3]['body'], true), + ); + $this->assertSame('1700000000000000000', $added->communityId); + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/communities/12', $this->transport->last()['url']); + } +} From f6218fef25479315e75841cbe06161c54edbca8f Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:48:24 +0200 Subject: [PATCH 09/14] feat(media): multipart upload --- src/Resource/MediaResource.php | 18 +++++++++++++++++- tests/MediaTest.php | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/Resource/MediaResource.php b/src/Resource/MediaResource.php index d16f0c3..9ff8d17 100644 --- a/src/Resource/MediaResource.php +++ b/src/Resource/MediaResource.php @@ -8,7 +8,7 @@ use Fopost\Sdk\Model\PresignedUpload; use Fopost\Sdk\Model\UploadLimits; -/** $client->media(): direct uploads to the media library. Needs the `posts` scope. */ +/** $client->media(): uploads to the media library. Needs the `posts` scope. */ final class MediaResource extends Resource { /** The largest file the account may upload, and which route carries it. */ @@ -91,4 +91,20 @@ public function uploadDirect( return $this->complete($upload->uploadId); } + + /** + * Upload files in one multipart request. With `$workspaceId` each file lands in the + * library and comes back with an `id`; without it the files are stored for a post only. + * + * @param array $files + * Paths or in-memory files. + * @return array + */ + public function upload(array $files, ?string $workspaceId = null): array + { + $fields = $workspaceId !== null ? ['workspaceId' => $workspaceId] : []; + $body = $this->http->requestMultipart('POST', '/media/upload', $fields, self::normalizeFiles($files), 'files'); + + return MediaAsset::listFrom(self::unwrap($body)); + } } diff --git a/tests/MediaTest.php b/tests/MediaTest.php index 7f7791b..85ac5b3 100644 --- a/tests/MediaTest.php +++ b/tests/MediaTest.php @@ -189,4 +189,25 @@ public function testUploadDirectStopsWhenThePutIsRejected(): void $this->assertSame(2, $this->transport->requestCount()); } + + public function testUploadSendsEveryFileAsMultipart(): void + { + $this->transport->push(200, ['data' => [ + ['id' => 'm_1', 'type' => 'image', 'name' => 'a.png', 'url' => 'https://cdn.test/a.png', 'size' => 3], + ]]); + + $assets = $this->client()->media()->upload( + [['filename' => 'a.png', 'contents' => 'abc', 'mimeType' => 'image/png']], + 'w_1', + ); + + $request = $this->transport->last(); + $this->assertSame('POST', $request['method']); + $this->assertSame('https://api.fopost.com/v1/media/upload', $request['url']); + $this->assertStringStartsWith('multipart/form-data; boundary=', $request['headers']['Content-Type']); + $this->assertStringContainsString('name="workspaceId"' . "\r\n\r\nw_1", (string) $request['body']); + $this->assertStringContainsString('name="files"; filename="a.png"', (string) $request['body']); + $this->assertStringContainsString("Content-Type: image/png\r\n\r\nabc", (string) $request['body']); + $this->assertSame('m_1', $assets[0]->id); + } } From 63e82450abe1a183255f13bf66cb5e9d293b91d3 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:48:24 +0200 Subject: [PATCH 10/14] feat(logs): request logs --- src/Client.php | 9 ++++++ src/Model/RequestLog.php | 52 ++++++++++++++++++++++++++++++++++ src/Model/RequestLogBucket.php | 32 +++++++++++++++++++++ src/Model/RequestLogPage.php | 47 ++++++++++++++++++++++++++++++ src/Resource/LogsResource.php | 42 +++++++++++++++++++++++++++ tests/LogsTest.php | 48 +++++++++++++++++++++++++++++++ 6 files changed, 230 insertions(+) create mode 100644 src/Model/RequestLog.php create mode 100644 src/Model/RequestLogBucket.php create mode 100644 src/Model/RequestLogPage.php create mode 100644 src/Resource/LogsResource.php create mode 100644 tests/LogsTest.php diff --git a/src/Client.php b/src/Client.php index b881604..8876558 100644 --- a/src/Client.php +++ b/src/Client.php @@ -22,6 +22,7 @@ use Fopost\Sdk\Resource\ActivityResource; use Fopost\Sdk\Resource\KnowledgeResource; use Fopost\Sdk\Resource\LabelsResource; +use Fopost\Sdk\Resource\LogsResource; use Fopost\Sdk\Resource\MediaResource; use Fopost\Sdk\Resource\PostsResource; use Fopost\Sdk\Resource\QueueResource; @@ -56,6 +57,7 @@ final class Client private readonly WorkspacesResource $workspaces; private readonly LabelsResource $labels; private readonly ActivityResource $activity; + private readonly LogsResource $logs; private readonly AiResource $ai; private readonly AutomationsResource $automations; private readonly InboxResource $inbox; @@ -98,6 +100,7 @@ public function __construct( $this->workspaces = new WorkspacesResource($this->http); $this->labels = new LabelsResource($this->http); $this->activity = new ActivityResource($this->http); + $this->logs = new LogsResource($this->http); $this->ai = new AiResource($this->http); $this->automations = new AutomationsResource($this->http); $this->inbox = new InboxResource($this->http); @@ -210,6 +213,12 @@ public function activity(): ActivityResource return $this->activity; } + /** The API requests made with your keys. */ + public function logs(): LogsResource + { + return $this->logs; + } + public function validate(): ValidateResource { return $this->validate; diff --git a/src/Model/RequestLog.php b/src/Model/RequestLog.php new file mode 100644 index 0000000..5d817ae --- /dev/null +++ b/src/Model/RequestLog.php @@ -0,0 +1,52 @@ + $logs + * @param array $buckets + */ + private function __construct( + array $raw, + public readonly array $logs, + /** Pass back as `$before` for the next page; null on the last page. */ + public readonly ?string $nextCursor, + public readonly bool $hasMore, + public readonly ?DateTimeImmutable $since, + public readonly int $total, + public readonly int $errors, + public readonly array $buckets, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $meta = self::nested($data, 'meta') ?? []; + $summary = self::nested($data, 'summary') ?? []; + + return new self( + $data, + RequestLog::listFrom(self::seq($data, 'data')), + self::str($meta, 'next_cursor'), + self::bool($meta, 'has_more') ?? false, + self::date($summary, 'since'), + self::int($summary, 'total') ?? 0, + self::int($summary, 'errors') ?? 0, + RequestLogBucket::listFrom(self::seq($summary, 'buckets')), + ); + } +} diff --git a/src/Resource/LogsResource.php b/src/Resource/LogsResource.php new file mode 100644 index 0000000..4d4d6a0 --- /dev/null +++ b/src/Resource/LogsResource.php @@ -0,0 +1,42 @@ +logs(): the API requests made with your keys, newest first. Needs the `workspaces` scope. */ +final class LogsResource extends Resource +{ + /** + * `$status` is ok or error; `$before` is the page's `nextCursor`. + */ + public function list( + ?string $workspaceId = null, + ?int $days = null, + ?string $status = null, + ?string $method = null, + ?int $statusCode = null, + ?string $platform = null, + ?string $route = null, + ?string $q = null, + ?int $limit = null, + ?string $before = null, + ): RequestLogPage { + $params = self::compact([ + 'workspace_id' => $workspaceId, + 'days' => $days, + 'status' => $status, + 'method' => $method, + 'status_code' => $statusCode, + 'platform' => $platform, + 'route' => $route, + 'q' => $q, + 'limit' => $limit, + 'before' => $before, + ]); + + return RequestLogPage::fromArray($this->http->get('/logs', $params)); + } +} diff --git a/tests/LogsTest.php b/tests/LogsTest.php new file mode 100644 index 0000000..7b23220 --- /dev/null +++ b/tests/LogsTest.php @@ -0,0 +1,48 @@ +transport->push(200, [ + 'data' => [[ + 'id' => 31, + 'workspace_id' => 'w_1', + 'time' => '2026-03-01T09:00:00Z', + 'auth_method' => 'api_key', + 'method' => 'POST', + 'route' => '/v1/posts', + 'path' => '/v1/posts', + 'status_code' => 422, + 'duration_ms' => 40, + 'platform' => null, + 'message' => 'content is required', + ]], + 'meta' => ['next_cursor' => '30', 'has_more' => true], + 'summary' => [ + 'since' => '2026-02-22T00:00:00Z', + 'total' => 10, + 'errors' => 1, + 'buckets' => [['at' => '2026-03-01T00:00:00Z', 'total' => 10, 'errors' => 1]], + ], + ]); + + $page = $this->client()->logs()->list('w_1', days: 7, status: 'error', limit: 50, before: '40'); + + $this->assertSame('GET', $this->transport->last()['method']); + $this->assertSame( + 'https://api.fopost.com/v1/logs?workspace_id=w_1&days=7&status=error&limit=50&before=40', + $this->transport->last()['url'], + ); + $this->assertSame(422, $page->logs[0]->statusCode); + $this->assertSame('/v1/posts', $page->logs[0]->route); + $this->assertSame('30', $page->nextCursor); + $this->assertTrue($page->hasMore); + $this->assertSame(1, $page->errors); + $this->assertSame(10, $page->buckets[0]->total); + } +} From 06872b2c458a06c8505a96ba99ed7277e40a7ef4 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:50:45 +0200 Subject: [PATCH 11/14] feat(analytics): overview, time series, top posts, labels, posts table, streak, demographics and inbox --- src/Model/AnalyticsAccountTotal.php | 45 ++++++++ src/Model/AnalyticsOverview.php | 78 +++++++++++++ src/Model/AnalyticsSeriesPoint.php | 40 +++++++ src/Model/AnalyticsTimeSeries.php | 29 +++++ src/Model/AudienceDemographics.php | 48 ++++++++ src/Model/DemographicsBucket.php | 31 ++++++ src/Model/InboxAnalytics.php | 70 ++++++++++++ src/Model/LabelAnalytics.php | 50 +++++++++ src/Model/PostingStreakDay.php | 34 ++++++ src/Model/PostsTablePage.php | 38 +++++++ src/Model/PostsTableRow.php | 44 ++++++++ src/Model/TopPost.php | 58 ++++++++++ src/Resource/AnalyticsResource.php | 163 +++++++++++++++++++++++++++- tests/AnalyticsTest.php | 149 +++++++++++++++++++++++++ 14 files changed, 874 insertions(+), 3 deletions(-) create mode 100644 src/Model/AnalyticsAccountTotal.php create mode 100644 src/Model/AnalyticsOverview.php create mode 100644 src/Model/AnalyticsSeriesPoint.php create mode 100644 src/Model/AnalyticsTimeSeries.php create mode 100644 src/Model/AudienceDemographics.php create mode 100644 src/Model/DemographicsBucket.php create mode 100644 src/Model/InboxAnalytics.php create mode 100644 src/Model/LabelAnalytics.php create mode 100644 src/Model/PostingStreakDay.php create mode 100644 src/Model/PostsTablePage.php create mode 100644 src/Model/PostsTableRow.php create mode 100644 src/Model/TopPost.php diff --git a/src/Model/AnalyticsAccountTotal.php b/src/Model/AnalyticsAccountTotal.php new file mode 100644 index 0000000..9ca698c --- /dev/null +++ b/src/Model/AnalyticsAccountTotal.php @@ -0,0 +1,45 @@ + $history Up to 30 days, oldest first. */ + private function __construct( + array $raw, + public readonly string $accountId, + public readonly string $platform, + public readonly ?string $username, + public readonly ?string $name, + public readonly ?string $avatar, + public readonly ?int $followers, + public readonly ?int $totalPosts, + public readonly ?DateTimeImmutable $fetchedAt, + public readonly array $history, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'account_id'), + self::requiredStr($data, 'platform'), + self::str($data, 'username'), + self::str($data, 'name'), + self::str($data, 'avatar'), + self::int($data, 'followers'), + self::int($data, 'total_posts'), + self::date($data, 'fetched_at'), + array_values(array_filter(self::seq($data, 'history'), is_array(...))), + ); + } +} diff --git a/src/Model/AnalyticsOverview.php b/src/Model/AnalyticsOverview.php new file mode 100644 index 0000000..985c534 --- /dev/null +++ b/src/Model/AnalyticsOverview.php @@ -0,0 +1,78 @@ + $deltas Percentage change vs the previous period, by metric. + * @param array{posts: int, follower_change: int, engagement: int} $todayStats + * @param array $platforms + * @param array $accounts + */ + private function __construct( + array $raw, + public readonly int $totalAccounts, + public readonly int $totalFollowers, + public readonly int $totalPosts, + public readonly int $totalEngagement, + public readonly int $totalImpressions, + public readonly int $totalReach, + public readonly int $totalLikes, + public readonly int $totalComments, + public readonly int $totalShares, + public readonly int $totalReposts, + public readonly int $totalSaves, + public readonly int $totalClicks, + public readonly int $totalVideoViews, + public readonly int $totalProfileViews, + /** Engagement over reach (or impressions); null without data. */ + public readonly ?float $engagementRate, + public readonly array $deltas, + public readonly array $todayStats, + public readonly array $platforms, + public readonly array $accounts, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $deltas = []; + foreach (self::map($data, 'deltas') as $metric => $delta) { + $deltas[(string) $metric] = is_int($delta) || is_float($delta) ? (float) $delta : null; + } + $today = self::map($data, 'today_stats'); + + return new self( + $data, + self::int($data, 'total_accounts') ?? 0, + self::int($data, 'total_followers') ?? 0, + self::int($data, 'total_posts') ?? 0, + self::int($data, 'total_engagement') ?? 0, + self::int($data, 'total_impressions') ?? 0, + self::int($data, 'total_reach') ?? 0, + self::int($data, 'total_likes') ?? 0, + self::int($data, 'total_comments') ?? 0, + self::int($data, 'total_shares') ?? 0, + self::int($data, 'total_reposts') ?? 0, + self::int($data, 'total_saves') ?? 0, + self::int($data, 'total_clicks') ?? 0, + self::int($data, 'total_video_views') ?? 0, + self::int($data, 'total_profile_views') ?? 0, + self::num($data, 'engagement_rate'), + $deltas, + [ + 'posts' => self::int($today, 'posts') ?? 0, + 'follower_change' => self::int($today, 'follower_change') ?? 0, + 'engagement' => self::int($today, 'engagement') ?? 0, + ], + array_values(array_filter(self::seq($data, 'platforms'), is_array(...))), + AnalyticsAccountTotal::listFrom(self::seq($data, 'accounts')), + ); + } +} diff --git a/src/Model/AnalyticsSeriesPoint.php b/src/Model/AnalyticsSeriesPoint.php new file mode 100644 index 0000000..37aa5b7 --- /dev/null +++ b/src/Model/AnalyticsSeriesPoint.php @@ -0,0 +1,40 @@ + $series */ + private function __construct( + array $raw, + public readonly int $days, + public readonly array $series, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'days') ?? 0, + AnalyticsSeriesPoint::listFrom(self::seq($data, 'series')), + ); + } +} diff --git a/src/Model/AudienceDemographics.php b/src/Model/AudienceDemographics.php new file mode 100644 index 0000000..0ee7acc --- /dev/null +++ b/src/Model/AudienceDemographics.php @@ -0,0 +1,48 @@ + $age + * @param array $gender + * @param array $country + * @param array $city + * @param array $contributingAccounts + * @param array $unsupportedAccounts + */ + private function __construct( + array $raw, + /** followers, engaged or reached. */ + public readonly string $audience, + public readonly array $age, + public readonly array $gender, + public readonly array $country, + public readonly array $city, + public readonly array $contributingAccounts, + public readonly array $unsupportedAccounts, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $dimensions = self::map($data, 'dimensions'); + + return new self( + $data, + self::requiredStr($data, 'audience'), + DemographicsBucket::listFrom(self::seq($dimensions, 'age')), + DemographicsBucket::listFrom(self::seq($dimensions, 'gender')), + DemographicsBucket::listFrom(self::seq($dimensions, 'country')), + DemographicsBucket::listFrom(self::seq($dimensions, 'city')), + array_values(array_filter(self::seq($data, 'contributing_accounts'), is_array(...))), + array_values(array_filter(self::seq($data, 'unsupported_accounts'), is_array(...))), + ); + } +} diff --git a/src/Model/DemographicsBucket.php b/src/Model/DemographicsBucket.php new file mode 100644 index 0000000..bc08799 --- /dev/null +++ b/src/Model/DemographicsBucket.php @@ -0,0 +1,31 @@ + $deltas Percentage change vs the previous period: received, sent, answered. + * @param array $series + * @param array $byPlatform + * @param array $byType + * @param array> $byAccount account_id, platform, username, name, avatar, received, sent + * @param array $responseTime + * @param array $heatmap + */ + private function __construct( + array $raw, + public readonly int $received, + public readonly int $sent, + /** Inbound items that got a reply. */ + public readonly int $answered, + /** Inbound items still unread or read, not resolved. */ + public readonly int $open, + public readonly int $conversations, + /** Median minutes from an inbound item to its first reply; null without replies. */ + public readonly ?float $medianResponseMinutes, + public readonly array $deltas, + public readonly array $series, + public readonly array $byPlatform, + public readonly array $byType, + public readonly array $byAccount, + public readonly array $responseTime, + public readonly array $heatmap, + public readonly ?string $timeZone, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $totals = self::map($data, 'totals'); + $deltas = []; + foreach (self::map($data, 'deltas') as $metric => $delta) { + $deltas[(string) $metric] = is_int($delta) || is_float($delta) ? (float) $delta : null; + } + $rows = static fn (string $name): array => array_values(array_filter(self::seq($data, $name), is_array(...))); + + return new self( + $data, + self::int($totals, 'received') ?? 0, + self::int($totals, 'sent') ?? 0, + self::int($totals, 'answered') ?? 0, + self::int($totals, 'open') ?? 0, + self::int($totals, 'conversations') ?? 0, + self::num($totals, 'median_response_minutes'), + $deltas, + $rows('series'), + $rows('by_platform'), + $rows('by_type'), + $rows('by_account'), + $rows('response_time'), + $rows('heatmap'), + self::str($data, 'time_zone'), + ); + } +} diff --git a/src/Model/LabelAnalytics.php b/src/Model/LabelAnalytics.php new file mode 100644 index 0000000..74a14bb --- /dev/null +++ b/src/Model/LabelAnalytics.php @@ -0,0 +1,50 @@ + $rows + * @param array $summary draft, scheduled, published, failed, pending, total + */ + private function __construct( + array $raw, + public readonly array $rows, + public readonly PageMeta $meta, + /** At least 1, so an empty list is one empty page. */ + public readonly int $totalPages, + public readonly array $summary, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $meta = self::nested($data, 'meta') ?? []; + + return new self( + $data, + PostsTableRow::listFrom(self::seq($data, 'data')), + PageMeta::fromArray($meta), + self::int($meta, 'total_pages') ?? 1, + array_map(intval(...), self::map($data, 'summary')), + ); + } +} diff --git a/src/Model/PostsTableRow.php b/src/Model/PostsTableRow.php new file mode 100644 index 0000000..45c8cbe --- /dev/null +++ b/src/Model/PostsTableRow.php @@ -0,0 +1,44 @@ + $platforms + * @param array $deliverySummary total, published, failed, pending + */ + private function __construct( + array $raw, + public readonly string $postId, + public readonly ?string $preview, + public readonly ?string $status, + public readonly ?DateTimeImmutable $createdAt, + public readonly ?DateTimeImmutable $scheduledAt, + public readonly array $platforms, + public readonly array $deliverySummary, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'post_id'), + self::str($data, 'preview'), + self::str($data, 'status'), + self::date($data, 'created_at'), + self::date($data, 'scheduled_at'), + array_values(array_filter(self::seq($data, 'platforms'), is_array(...))), + array_map(intval(...), self::map($data, 'delivery_summary')), + ); + } +} diff --git a/src/Model/TopPost.php b/src/Model/TopPost.php new file mode 100644 index 0000000..ad4cda0 --- /dev/null +++ b/src/Model/TopPost.php @@ -0,0 +1,58 @@ + $platforms + * @param array $labels Always empty for native posts. + * @param array $metrics engagements, impressions, reach, likes, comments, shares, reposts, + * clicks, saves, video_views + */ + private function __construct( + array $raw, + public readonly int $rank, + /** The FoPost post id, or null for a post made natively on the network. */ + public readonly ?string $postId, + public readonly ?string $externalPostId, + /** fopost or platform. */ + public readonly string $source, + public readonly ?string $preview, + public readonly ?string $permalink, + public readonly ?string $thumbnailUrl, + public readonly ?string $status, + public readonly ?DateTimeImmutable $createdAt, + public readonly array $platforms, + public readonly array $labels, + public readonly array $metrics, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::int($data, 'rank') ?? 0, + self::str($data, 'post_id'), + self::str($data, 'external_post_id'), + self::requiredStr($data, 'source'), + self::str($data, 'preview'), + self::str($data, 'permalink'), + self::str($data, 'thumbnail_url'), + self::str($data, 'status'), + self::date($data, 'created_at'), + array_values(array_filter(self::seq($data, 'platforms'), is_array(...))), + array_values(array_filter(self::seq($data, 'labels'), is_array(...))), + array_map(intval(...), self::map($data, 'metrics')), + ); + } +} diff --git a/src/Resource/AnalyticsResource.php b/src/Resource/AnalyticsResource.php index 0ca7862..ee0950c 100644 --- a/src/Resource/AnalyticsResource.php +++ b/src/Resource/AnalyticsResource.php @@ -4,22 +4,179 @@ namespace Fopost\Sdk\Resource; +use Fopost\Sdk\Model\AnalyticsOverview; +use Fopost\Sdk\Model\AnalyticsTimeSeries; +use Fopost\Sdk\Model\AudienceDemographics; use Fopost\Sdk\Model\CollectPostResult; use Fopost\Sdk\Model\ContentDecayReport; +use Fopost\Sdk\Model\InboxAnalytics; +use Fopost\Sdk\Model\LabelAnalytics; use Fopost\Sdk\Model\MetricChangePage; use Fopost\Sdk\Model\NativePost; use Fopost\Sdk\Model\Page; use Fopost\Sdk\Model\PostTimeline; use Fopost\Sdk\Model\PostingFrequencyReport; +use Fopost\Sdk\Model\PostingStreakDay; +use Fopost\Sdk\Model\PostsTablePage; +use Fopost\Sdk\Model\TopPost; /** - * $client->analytics(): deeper posting analytics. + * $client->analytics(): the dashboard's analytics, and the deeper readings beneath them. * - * Derived from the repeated readings the platform collector takes of every - * post as it ages. Needs the `analytics` scope. + * The overview, time series, top posts, labels, posts table, streak, + * demographics and inbox calls answer what the dashboard shows. `decay`, + * `frequency`, `timeline` and `changes` are derived from the repeated readings + * the platform collector takes of every post as it ages. Needs the + * `analytics` scope. */ final class AnalyticsResource extends Resource { + /** Totals, deltas and per-account follower history for the period (`$days` defaults to 30). */ + public function overview( + ?int $days = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): AnalyticsOverview { + $query = self::compact(['days' => $days, 'workspace_id' => $workspaceId, 'account_id' => $accountId]); + + return AnalyticsOverview::fromArray(self::unwrap($this->http->get('/analytics/overview', $query))); + } + + /** Daily totals. Give `$from` and `$to` (YYYY-MM-DD) for an exact range instead of `$days`. */ + public function timeSeries( + ?int $days = null, + ?string $from = null, + ?string $to = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): AnalyticsTimeSeries { + $query = self::compact([ + 'days' => $days, + 'from' => $from, + 'to' => $to, + 'workspace_id' => $workspaceId, + 'account_id' => $accountId, + ]); + + return AnalyticsTimeSeries::fromArray(self::unwrap($this->http->get('/analytics/time-series', $query))); + } + + /** + * The posts that earned the most. `$sort` picks the metric; `$label` keeps one label's posts. + * + * @return array + */ + public function topPosts( + ?int $limit = null, + ?int $days = null, + ?string $from = null, + ?string $to = null, + ?string $sort = null, + ?string $label = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): array { + $query = self::compact([ + 'limit' => $limit, + 'days' => $days, + 'from' => $from, + 'to' => $to, + 'sort' => $sort, + 'label' => $label, + 'workspace_id' => $workspaceId, + 'account_id' => $accountId, + ]); + + return TopPost::listFrom(self::unwrap($this->http->get('/analytics/top-posts', $query))); + } + + /** + * What each label's posts earned, so a campaign can be read as a whole. + * + * @return array + */ + public function labels( + ?int $days = null, + ?string $from = null, + ?string $to = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): array { + $query = self::compact([ + 'days' => $days, + 'from' => $from, + 'to' => $to, + 'workspace_id' => $workspaceId, + 'account_id' => $accountId, + ]); + + return LabelAnalytics::listFrom(self::unwrap($this->http->get('/analytics/labels', $query))); + } + + /** Posts with where each delivery stands, one page at a time, plus status counts for the whole set. */ + public function postsTable( + int $page = 1, + int $perPage = 20, + ?int $days = null, + ?string $from = null, + ?string $to = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): PostsTablePage { + $query = self::compact([ + 'page' => $page, + 'per_page' => $perPage, + 'days' => $days, + 'from' => $from, + 'to' => $to, + 'workspace_id' => $workspaceId, + 'account_id' => $accountId, + ]); + + return PostsTablePage::fromArray($this->http->get('/analytics/posts-table', $query)); + } + + /** + * How many posts went out each day. + * + * @return array + */ + public function postingStreak(?string $workspaceId = null): array + { + $query = self::compact(['workspace_id' => $workspaceId]); + $body = self::asArray($this->http->get('/analytics/posting-streak', $query)); + + return PostingStreakDay::listFrom($body['streak'] ?? []); + } + + /** Who the audience is. `$audience` is followers, engaged or reached. */ + public function demographics( + ?string $audience = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): AudienceDemographics { + $query = self::compact(['audience' => $audience, 'workspace_id' => $workspaceId, 'account_id' => $accountId]); + + return AudienceDemographics::fromArray(self::unwrap($this->http->get('/analytics/demographics', $query))); + } + + /** Inbox volume and response times. `$tz` is the IANA zone the heatmap and series are bucketed in. */ + public function inbox( + ?int $days = null, + ?string $tz = null, + ?string $workspaceId = null, + ?string $accountId = null, + ): InboxAnalytics { + $query = self::compact([ + 'days' => $days, + 'tz' => $tz, + 'workspace_id' => $workspaceId, + 'account_id' => $accountId, + ]); + + return InboxAnalytics::fromArray(self::unwrap($this->http->get('/analytics/inbox', $query))); + } + /** * How engagement accumulates with a post's age, and where the half-life falls. * diff --git a/tests/AnalyticsTest.php b/tests/AnalyticsTest.php index 5bdff59..b2f19f7 100644 --- a/tests/AnalyticsTest.php +++ b/tests/AnalyticsTest.php @@ -208,4 +208,153 @@ public function testNativePostsReturnsAPage(): void $this->assertSame('https://x.com/acme/status/1', $page->items[0]->permalink); $this->assertSame(90, $page->items[0]->metrics->engagements); } + + public function testOverviewTimeSeriesAndTopPostsReadTheDashboardNumbers(): void + { + $this->transport->push(200, [ + 'total_accounts' => 2, + 'total_followers' => 1200, + 'total_posts' => 8, + 'total_engagement' => 300, + 'engagement_rate' => 0.05, + 'deltas' => ['followers' => 2.5, 'posts' => null], + 'today_stats' => ['posts' => 1, 'follower_change' => 3, 'engagement' => 20], + 'platforms' => [['platform' => 'bluesky', 'accounts' => 1, 'followers' => 200]], + 'accounts' => [[ + 'account_id' => 'a_1', + 'platform' => 'bluesky', + 'username' => 'yourbrand', + 'name' => 'Your Brand', + 'followers' => 200, + 'history' => [['date' => '2026-03-01', 'followers' => 198]], + ]], + ]); + $this->transport->push(200, [ + 'days' => 7, + 'series' => [['date' => '2026-03-01', 'engagements' => 10, 'impressions' => 100, 'posts' => 1]], + ]); + $this->transport->push(200, ['data' => [[ + 'rank' => 1, + 'post_id' => 'p_1', + 'source' => 'fopost', + 'preview' => 'Hello', + 'platforms' => [['platform' => 'bluesky', 'username' => 'yourbrand', 'url' => null, 'removed' => false]], + 'labels' => [], + 'metrics' => ['engagements' => 40, 'impressions' => 900], + ]]]); + + $analytics = $this->client()->analytics(); + $overview = $analytics->overview(days: 30, workspaceId: 'w_1'); + $series = $analytics->timeSeries(from: '2026-03-01', to: '2026-03-07', accountId: 'a_1'); + $top = $analytics->topPosts(limit: 5, sort: 'engagements', label: 'l_1'); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/overview?days=30&workspace_id=w_1', + $this->transport->requests[0]['url'], + ); + $this->assertSame(1200, $overview->totalFollowers); + $this->assertSame(0.05, $overview->engagementRate); + $this->assertSame(['followers' => 2.5, 'posts' => null], $overview->deltas); + $this->assertSame(3, $overview->todayStats['follower_change']); + $this->assertSame(198, $overview->accounts[0]->history[0]['followers']); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/time-series?from=2026-03-01&to=2026-03-07&account_id=a_1', + $this->transport->requests[1]['url'], + ); + $this->assertSame(7, $series->days); + $this->assertSame(100, $series->series[0]->impressions); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/top-posts?limit=5&sort=engagements&label=l_1', + $this->transport->last()['url'], + ); + $this->assertSame('p_1', $top[0]->postId); + $this->assertSame(40, $top[0]->metrics['engagements']); + $this->assertFalse($top[0]->platforms[0]['removed']); + } + + public function testLabelsTableStreakDemographicsAndInboxAreRead(): void + { + $this->transport->push(200, ['data' => [[ + 'label_id' => 'l_1', + 'name' => 'Launch', + 'color' => '#0070f3', + 'post_count' => 4, + 'engagements' => 80, + 'engagement_rate' => 0.1, + 'follower_delta' => null, + ]]]); + $this->transport->push(200, [ + 'data' => [[ + 'post_id' => 'p_1', + 'preview' => 'Hello', + 'status' => 'published', + 'platforms' => [ + ['platform' => 'bluesky', 'username' => 'y', 'url' => null, 'delivery_status' => 'published'], + ], + 'delivery_summary' => ['total' => 1, 'published' => 1, 'failed' => 0, 'pending' => 0], + ]], + 'meta' => ['page' => 2, 'per_page' => 10, 'total' => 11, 'total_pages' => 2], + 'summary' => ['published' => 11, 'total' => 11], + ]); + $this->transport->push(200, ['streak' => [['date' => '2026-03-01', 'count' => 2, 'published_count' => 2]]]); + $this->transport->push(200, [ + 'audience' => 'followers', + 'dimensions' => ['age' => [['key' => '25-34', 'value' => 40, 'share' => 0.4]], 'gender' => []], + 'contributing_accounts' => [['account_id' => 'a_1', 'platform' => 'instagram', 'username' => 'y']], + 'unsupported_accounts' => [], + ]); + $this->transport->push(200, [ + 'totals' => ['received' => 30, 'sent' => 12, 'answered' => 10, 'open' => 5, 'conversations' => 8, + 'median_response_minutes' => 42.5], + 'deltas' => ['received' => -10], + 'series' => [['date' => '2026-03-01', 'received' => 3, 'sent' => 1, 'answered' => 1]], + 'by_type' => [['type' => 'comment', 'count' => 20]], + 'heatmap' => [['weekday' => 1, 'hour' => 9, 'count' => 4]], + 'time_zone' => 'Europe/Zagreb', + ]); + + $analytics = $this->client()->analytics(); + $labels = $analytics->labels(days: 90); + $table = $analytics->postsTable(2, 10, workspaceId: 'w_1'); + $streak = $analytics->postingStreak('w_1'); + $demographics = $analytics->demographics('followers', accountId: 'a_1'); + $inbox = $analytics->inbox(days: 30, tz: 'Europe/Zagreb'); + + $this->assertSame('https://api.fopost.com/v1/analytics/labels?days=90', $this->transport->requests[0]['url']); + $this->assertSame(4, $labels[0]->postCount); + $this->assertNull($labels[0]->followerDelta); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/posts-table?page=2&per_page=10&workspace_id=w_1', + $this->transport->requests[1]['url'], + ); + $this->assertSame(2, $table->meta->currentPage); + $this->assertSame(2, $table->totalPages); + $this->assertSame('published', $table->rows[0]->platforms[0]['delivery_status']); + $this->assertSame(11, $table->summary['total']); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/posting-streak?workspace_id=w_1', + $this->transport->requests[2]['url'], + ); + $this->assertSame(2, $streak[0]->publishedCount); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/demographics?audience=followers&account_id=a_1', + $this->transport->requests[3]['url'], + ); + $this->assertSame(0.4, $demographics->age[0]->share); + $this->assertSame('instagram', $demographics->contributingAccounts[0]['platform']); + + $this->assertSame( + 'https://api.fopost.com/v1/analytics/inbox?days=30&tz=Europe%2FZagreb', + $this->transport->last()['url'], + ); + $this->assertSame(42.5, $inbox->medianResponseMinutes); + $this->assertSame(['received' => -10.0], $inbox->deltas); + $this->assertSame(20, $inbox->byType[0]['count']); + $this->assertSame('Europe/Zagreb', $inbox->timeZone); + } } From cd5812356a8e58a712d8064a33a0e4aea6ac7aa4 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:51:39 +0200 Subject: [PATCH 12/14] chore(release): 0.4.0 --- CHANGELOG.md | 32 ++++++++++++ CLAUDE.md | 18 ++++--- README.md | 139 +++++++++++++++++++++++++++++++++++++++++++++++++ src/Client.php | 2 +- 4 files changed, 182 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b198668..1183eff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,38 @@ All notable changes to `fopost/sdk` are documented here. +## 0.4.0 - 2026-10-18 + +### Added + +- `$client->queue()` wraps the posting queue: `listSlots`, `createSlot`, `updateSlot`, + `deleteSlot`, `next` and `preview`, with `QueueSlot`, `QueueMove`, `QueueSlotUpdate` and + `QueueSlotDeletion`. `posts()->create()` and `update()` take `schedule: 'queue'`. +- `$client->posts()->unpublish()` takes a published post down everywhere and answers an + `UnpublishResult` with one `PlatformRemoval` per network. `validateBulkImport()`, + `commitBulkImport()` and `rollbackBulkImport()` wrap the CSV import. +- `$client->connectSessions()` creates and reads hosted connect links (`ConnectSession`). +- `$client->webhooks()` manages endpoints (`list`, `create`, `update`, `delete`, `test`) and + their delivery log (`listDeliveries`, `getDelivery`, `redeliver`), with `Webhook` and + `WebhookDelivery`. +- `$client->automations()` wraps `/automations`: `list`, `stats`, `get`, `create`, `update`, + `delete`, `toggle`, versions (`listVersions`, `getVersion`, `restoreVersion`) and runs + (`listRuns`, `getRun`), with `Automation`, `AutomationStep`, `AutomationStats`, + `AutomationVersion`, `AutomationNodeRef`, `AutomationRestore`, `AutomationRun`, + `AutomationRunLog` and `AutomationToggle`. +- `$client->workspaces()->create()`, `update()` and `delete()`. `Workspace` carries + `connectRedirectDomains` and `updatedAt`. +- `$client->accounts()` X communities: `listCommunities`, `syncCommunities`, + `searchCommunities`, `addCommunity` and `removeCommunity` (`XCommunity`, `XCommunityMatch`). +- `$client->logs()->list()` reads the request log into `RequestLogPage` (`RequestLog`, + `RequestLogBucket`). +- `$client->analytics()` dashboard calls: `overview`, `timeSeries`, `topPosts`, `labels`, + `postsTable`, `postingStreak`, `demographics` and `inbox`, with `AnalyticsOverview`, + `AnalyticsAccountTotal`, `AnalyticsTimeSeries`, `AnalyticsSeriesPoint`, `TopPost`, + `LabelAnalytics`, `PostsTablePage`, `PostsTableRow`, `PostingStreakDay`, + `AudienceDemographics`, `DemographicsBucket` and `InboxAnalytics`. +- `$client->media()->upload()` sends files through the API in one multipart request. + ## 0.3.0 - 2026-10-18 ### Removed diff --git a/CLAUDE.md b/CLAUDE.md index 5a3056a..57538d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ exception per error status. PSR-4 autoload root `Fopost\Sdk\` → `src/`. - **PHP >= 8.1.** Extensions `ext-curl` and `ext-json` are the only runtime requirements — there are no Composer runtime dependencies, and none may be added. -- Version `0.3.0`, declared in `Fopost\Sdk\Client::VERSION`. `composer.json` carries no +- Version `0.4.0`, declared in `Fopost\Sdk\Client::VERSION`. `composer.json` carries no `version` key (Packagist reads the git tag). ## Downstream Packages @@ -54,9 +54,10 @@ src/ Response.php status + lowercased headers + raw body, pre-decode Resource/ Resource.php base: unwrap/compact/asArray/iso helpers - PostsResource.php AccountsResource.php AccountGroupsResource.php WorkspacesResource.php - LabelsResource.php AiResource.php InboxResource.php AdsResource.php MediaResource.php - ValidateResource.php + PostsResource.php QueueResource.php AccountsResource.php ConnectSessionsResource.php + AccountGroupsResource.php WorkspacesResource.php LabelsResource.php AiResource.php + AutomationsResource.php InboxResource.php AdsResource.php MediaResource.php + ValidateResource.php WebhooksResource.php AnalyticsResource.php LogsResource.php ... Model/ Model.php base: reads both wire casings, keeps the untouched payload on ->raw Page.php PageMeta.php Post.php SocialAccount.php Workspace.php Label.php ... @@ -90,10 +91,11 @@ throws through `ErrorFactory` or returns the decoded body → the resource calls - `PostsResource::iterate()` / `iteratePages()` are generators that page through the list endpoint; `Page` is `IteratorAggregate + Countable + ArrayAccess` and read-only. -**Resources wired today:** `posts`, `accounts`, `accountGroups`, `workspaces`, `labels`, `ai`, -`inbox`, `contacts`, `broadcasts`, `sequences`, `ads`, `media`, `validate`. There is no `communities`, `webhooks`, `analytics`, or -`automations` resource here — reach those through the escape hatch `Client::request()` until one -is added. +**Resources wired today:** `posts`, `queue`, `accounts`, `connectSessions`, `accountGroups`, +`workspaces`, `labels`, `ai`, `automations`, `inbox`, `contacts`, `broadcasts`, `sequences`, `blog`, +`knowledge`, `ads`, `blogs`, `media`, `validate`, `webhooks`, `whatsapp`, `analytics`, `googleBusiness`, +`activity`, `logs`. Anything else goes through the escape hatch `Client::request()` until a +resource is added. `scripts/sdk-gaps.mjs` in `fopost-api-collections` lists what is still unwrapped. - `inbox` (scope `inbox`) covers `/inbox`, `/inbox/posts`, `/inbox/conversations`, `unread-count`, `accounts`, `platforms`, `read`, `refresh`, `approvals` (+ `approve`/`reject`, integer ids), and diff --git a/README.md b/README.md index 6a2ad3c..d89af8c 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,36 @@ foreach ($client->posts()->deliveries($draft->id) as $delivery) { } ``` +Drop a post into the next free posting slot instead of picking a time, take a +published post down everywhere, or create many posts from a CSV: + +```php +$client->posts()->create($workspaceId, 'Queued', accounts: [$accountId], schedule: 'queue'); +$client->posts()->update($post->id, schedule: 'queue'); + +$result = $client->posts()->unpublish($post->id); +echo $result->postStatus; // "unpublished"; $result->deliveries[0]->removed per network + +$check = $client->posts()->validateBulkImport($workspaceId, 'posts.csv'); +if ($check->invalidRows === 0) { + $batch = $client->posts()->commitBulkImport($workspaceId, 'posts.csv'); + $client->posts()->rollbackBulkImport($batch->batchId); // deletes everything it created +} +``` + +## Queue + +The weekly slots a post created with `schedule: 'queue'` lands in. Needs the `posts` scope. + +```php +$slot = $client->queue()->createSlot($workspaceId, weekday: 1, time: '09:00', timezone: 'Europe/Zagreb'); +$client->queue()->updateSlot($slot->id, time: '10:00'); // ->moved lists the posts that shifted +$client->queue()->listSlots($workspaceId); +$client->queue()->next($workspaceId); // DateTimeImmutable or null +$client->queue()->preview($workspaceId, count: 5); // the next five times +$client->queue()->deleteSlot($slot->id); +``` + ## Accounts ```php @@ -196,6 +226,33 @@ $flairs = $client->accounts()->listRedditFlairs('acc_1', 'webdev'); $client->accounts()->setRedditDefaultSubreddit('acc_1', 'webdev'); ``` +X communities linked to an account: + +```php +$client->accounts()->syncCommunities($accountId); +$matches = $client->accounts()->searchCommunities($accountId, 'PHP'); +$community = $client->accounts()->addCommunity($accountId, $matches[0]->id); +$client->accounts()->removeCommunity($accountId, $community->id); +``` + +## Connect sessions + +Hosted connect links for your own users. Send the user to `url`, then poll until the +session is `used`. Needs the `accounts` scope. + +```php +$session = $client->connectSessions()->create( + externalUserId: 'user-42', + platforms: ['linkedin', 'threads'], + workspaceId: $workspaceId, + redirectUrl: 'https://yourbrand.com/connected', +); +echo $session->url; + +$session = $client->connectSessions()->get($session->id); +echo $session->status, ' ', $session->accountId; +``` + ## Google Business Profile Manage a connected Business Profile location: the profile, attributes, food menus, services, photos, action links, verification and performance. @@ -238,6 +295,12 @@ $workspace = $client->workspaces()->get($workspaceId); echo $workspace->name, ' ', $workspace->timezone, PHP_EOL; ``` +```php +$workspace = $client->workspaces()->create('Client', type: 'CLIENT', timezone: 'Europe/Zagreb'); +$client->workspaces()->update($workspace->id, requireApproval: true, connectRedirectDomains: ['yourbrand.com']); +$client->workspaces()->delete($workspace->id); // 409 while accounts are still connected +``` + ## Labels ```php @@ -737,6 +800,12 @@ $upload = $client->media()->presign($workspaceId, 'clip.mp4', 'video/mp4', files $asset = $client->media()->complete($upload->uploadId); ``` +Or send the bytes through the API in one multipart request: + +```php +$assets = $client->media()->upload(['logo.png', 'clip.mp4'], $workspaceId); +``` + A file over the limit is a `413` with `error: file_too_large`; it arrives as an `ApiException` whose `getBody()['max_file_bytes']` says what would have fit, and `getBody()['upgrade_url']` where to raise it. @@ -827,6 +896,21 @@ hand on the network works the same way: ```php $client->analytics()->timeline('https://x.com/acme/status/1'); +The numbers the dashboard shows: + +```php +$overview = $client->analytics()->overview(days: 30, workspaceId: $workspaceId); +echo $overview->totalFollowers, ' ', $overview->engagementRate, PHP_EOL; + +$series = $client->analytics()->timeSeries(from: '2026-03-01', to: '2026-03-31'); +$top = $client->analytics()->topPosts(limit: 10, sort: 'engagements'); +$labels = $client->analytics()->labels(days: 90); +$table = $client->analytics()->postsTable(page: 1, perPage: 20); +$streak = $client->analytics()->postingStreak($workspaceId); +$audience = $client->analytics()->demographics('followers', accountId: $accountId); +$inbox = $client->analytics()->inbox(days: 30, tz: 'Europe/Zagreb'); +``` + ## Activity What happened in a workspace, newest first. Needs the `analytics` scope. @@ -846,6 +930,61 @@ signed-in devices. Those rows are append-only and never expire. $audit = $client->activity()->list('w_1', 'security'); ``` +## Logs + +The API requests made with your keys, newest first, with error counts per bucket. Needs the +`workspaces` scope. + +```php +$page = $client->logs()->list($workspaceId, days: 7, status: 'error'); +$page->logs[0]->route; // "/v1/posts/{id}" +$page->logs[0]->statusCode; // 422 +$page->nextCursor; // pass back as $before for the next page +``` + +## Webhooks + +The endpoints FoPost sends events to, and their delivery log. Verify what arrives with +`Fopost\Sdk\Webhooks::verify()`. Needs the `webhooks` scope. + +```php +$hook = $client->webhooks()->create($workspaceId, 'https://yourbrand.com/hooks', ['post.published']); +echo $hook->secret; // returned once + +$client->webhooks()->update($hook->id, events: ['post.published', 'post.failed'], active: true); +$client->webhooks()->test($hook->id); + +foreach ($client->webhooks()->listDeliveries($hook->id, status: 'failed') as $delivery) { + $client->webhooks()->redeliver($hook->id, $delivery->id); +} +$delivery = $client->webhooks()->getDelivery($hook->id, $deliveryId); // ->payload as sent +$client->webhooks()->delete($hook->id); +``` + +## Automations + +Triggers and the step chains they run. Needs the `automations` scope. + +```php +$automation = $client->automations()->create( + $workspaceId, + 'Cross-post', + 'content_created', + ['accountIds' => [$accountId]], + steps: [['actionType' => 'publish', 'actionConfig' => ['accountIds' => [$otherAccountId]]]], +); +$client->automations()->update($automation->id, active: false); +$client->automations()->toggle($automation->id); +$client->automations()->stats(); + +$versions = $client->automations()->listVersions($automation->id); +$client->automations()->restoreVersion($automation->id, $versions->items[1]->version); + +$runs = $client->automations()->listRuns($automation->id); +$run = $client->automations()->getRun($automation->id, $runs->items[0]->id); // ->logs per step +$client->automations()->delete($automation->id); +``` + ## Blogs, articles and products Content a connected site already owns: the articles on a WordPress site or a diff --git a/src/Client.php b/src/Client.php index 8876558..be7d8a0 100644 --- a/src/Client.php +++ b/src/Client.php @@ -45,7 +45,7 @@ */ final class Client { - public const VERSION = '0.3.0'; + public const VERSION = '0.4.0'; public const DEFAULT_BASE_URL = HttpClient::DEFAULT_BASE_URL; private readonly HttpClient $http; From 7d8ac449eef9cf9e7041b6f8d00cd51edeabf6db Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:52:39 +0200 Subject: [PATCH 13/14] feat(media): list and delete library files --- CHANGELOG.md | 4 ++- README.md | 3 +++ src/Model/MediaAsset.php | 41 +++++++++++++++++++++++++++++ src/Resource/MediaResource.php | 47 ++++++++++++++++++++++++++++++++++ tests/MediaTest.php | 36 ++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1183eff..6869507 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,9 @@ All notable changes to `fopost/sdk` are documented here. `AnalyticsAccountTotal`, `AnalyticsTimeSeries`, `AnalyticsSeriesPoint`, `TopPost`, `LabelAnalytics`, `PostsTablePage`, `PostsTableRow`, `PostingStreakDay`, `AudienceDemographics`, `DemographicsBucket` and `InboxAnalytics`. -- `$client->media()->upload()` sends files through the API in one multipart request. +- `$client->media()->upload()` sends files through the API in one multipart request; + `list()` pages through the library and `delete()` removes a file. `MediaAsset` carries every + library field (`mimeType`, `tags`, `brandRole`, `hasPersonConsent`, `share`, ...). ## 0.3.0 - 2026-10-18 diff --git a/README.md b/README.md index d89af8c..7a7c3aa 100644 --- a/README.md +++ b/README.md @@ -804,6 +804,9 @@ Or send the bytes through the API in one multipart request: ```php $assets = $client->media()->upload(['logo.png', 'clip.mp4'], $workspaceId); + +$page = $client->media()->list($workspaceId, type: 'image', brandRole: 'logo'); +$client->media()->delete($page->items[0]->id); ``` A file over the limit is a `413` with `error: file_too_large`; it arrives as an `ApiException` whose diff --git a/src/Model/MediaAsset.php b/src/Model/MediaAsset.php index d2919c3..7595b9a 100644 --- a/src/Model/MediaAsset.php +++ b/src/Model/MediaAsset.php @@ -4,17 +4,42 @@ namespace Fopost\Sdk\Model; +use DateTimeImmutable; + /** A file in the media library. */ final class MediaAsset extends Model { + /** + * @param array $tags + * @param array{url: string, created_at: string, created_by_name: ?string, source: string}|null $share + * The live share link; present only when listing with `shared: true`. + */ private function __construct( array $raw, public readonly string $id, public readonly string $type, public readonly string $name, + /** The asset's identity; store this on a post. */ public readonly string $url, + /** Permanent, membership-checked read URL. */ public readonly ?string $previewUrl, public readonly ?int $size, + public readonly ?string $workspaceId, + public readonly ?string $visibility, + public readonly ?string $mimeType, + public readonly ?string $altText, + public readonly ?string $altTextSource, + public readonly array $tags, + public readonly ?string $folderId, + public readonly ?string $origin, + public readonly ?string $sourceUrl, + public readonly ?DateTimeImmutable $syncedAt, + public readonly ?string $brandRole, + public readonly ?string $brandVoiceId, + public readonly ?string $generationRunId, + public readonly ?bool $hasPersonConsent, + public readonly ?DateTimeImmutable $createdAt, + public readonly ?array $share, ) { parent::__construct($raw); } @@ -31,6 +56,22 @@ public static function fromArray(mixed $data): static self::requiredStr($data, 'url'), self::str($data, 'preview_url'), self::int($data, 'size'), + self::str($data, 'workspace_id'), + self::str($data, 'visibility'), + self::str($data, 'mime_type'), + self::str($data, 'alt_text'), + self::str($data, 'alt_text_source'), + array_values(array_map(strval(...), self::seq($data, 'tags'))), + self::str($data, 'folder_id'), + self::str($data, 'origin'), + self::str($data, 'source_url'), + self::date($data, 'synced_at'), + self::str($data, 'brand_role'), + self::str($data, 'brand_voice_id'), + self::str($data, 'generation_run_id'), + self::bool($data, 'has_person_consent'), + self::date($data, 'created_at'), + self::nested($data, 'share'), ); } } diff --git a/src/Resource/MediaResource.php b/src/Resource/MediaResource.php index 9ff8d17..4c5c03d 100644 --- a/src/Resource/MediaResource.php +++ b/src/Resource/MediaResource.php @@ -5,12 +5,59 @@ namespace Fopost\Sdk\Resource; use Fopost\Sdk\Model\MediaAsset; +use Fopost\Sdk\Model\Page; use Fopost\Sdk\Model\PresignedUpload; use Fopost\Sdk\Model\UploadLimits; /** $client->media(): uploads to the media library. Needs the `posts` scope. */ final class MediaResource extends Resource { + /** + * The library, newest first. `$type` is image, video, gif or document; `$shared` of true + * keeps only assets with a live share link and fills `->share`. + * + * @return Page + */ + public function list( + ?string $workspaceId = null, + int $page = 1, + int $perPage = 20, + ?string $folderId = null, + ?string $search = null, + ?string $tag = null, + ?string $type = null, + ?string $url = null, + ?string $brandRole = null, + ?string $brandVoiceId = null, + ?string $generationRunId = null, + ?string $origin = null, + ?bool $shared = null, + ): Page { + $query = self::compact([ + 'workspace_id' => $workspaceId, + 'page' => $page, + 'per_page' => $perPage, + 'folder_id' => $folderId, + 'search' => $search, + 'tag' => $tag, + 'type' => $type, + 'url' => $url, + 'brand_role' => $brandRole, + 'brand_voice_id' => $brandVoiceId, + 'generation_run_id' => $generationRunId, + 'origin' => $origin, + 'shared' => $shared === null ? null : ($shared ? 'true' : 'false'), + ]); + + return self::page(MediaAsset::class, $this->http->get('/media', $query)); + } + + /** Remove a file from the library. */ + public function delete(string $mediaId): void + { + $this->http->delete("/media/{$mediaId}"); + } + /** The largest file the account may upload, and which route carries it. */ public function limits(?string $workspaceId = null): UploadLimits { diff --git a/tests/MediaTest.php b/tests/MediaTest.php index 85ac5b3..752a793 100644 --- a/tests/MediaTest.php +++ b/tests/MediaTest.php @@ -210,4 +210,40 @@ public function testUploadSendsEveryFileAsMultipart(): void $this->assertStringContainsString("Content-Type: image/png\r\n\r\nabc", (string) $request['body']); $this->assertSame('m_1', $assets[0]->id); } + + public function testListAndDeleteReachTheLibrary(): void + { + $this->transport->push(200, [ + 'data' => [[ + 'id' => 'm_1', + 'workspace_id' => 'w_1', + 'name' => 'logo.png', + 'url' => 'https://cdn.test/logo.png', + 'preview_url' => 'https://api.fopost.com/v1/media/m_1/file', + 'type' => 'image', + 'mime_type' => 'image/png', + 'size' => 3, + 'tags' => ['brand'], + 'brand_role' => 'logo', + 'has_person_consent' => false, + 'created_at' => '2026-03-01T09:00:00Z', + ]], + 'meta' => ['page' => 1, 'per_page' => 20, 'total' => 1, 'total_pages' => 1], + ]); + $this->transport->push(204); + + $page = $this->client()->media()->list('w_1', type: 'image', shared: false); + $this->client()->media()->delete('m_1'); + + $this->assertSame( + 'https://api.fopost.com/v1/media?workspace_id=w_1&page=1&per_page=20&type=image&shared=false', + $this->transport->requests[0]['url'], + ); + $this->assertSame(1, $page->meta->total); + $this->assertSame('logo', $page->items[0]->brandRole); + $this->assertSame(['brand'], $page->items[0]->tags); + $this->assertSame('image/png', $page->items[0]->mimeType); + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/media/m_1', $this->transport->last()['url']); + } } From 6900423fe055813261dfe2c44484aa84ac069414 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 21:07:03 +0200 Subject: [PATCH 14/14] feat(accounts): validate, refresh token, primary toggle and analytics history; workspace analytics --- CHANGELOG.md | 5 ++- src/Model/AccountAnalyticsHistory.php | 33 ++++++++++++++++++++ src/Model/AccountPrimary.php | 21 +++++++++++++ src/Model/AccountSnapshot.php | 38 ++++++++++++++++++++++ src/Model/AccountValidation.php | 45 +++++++++++++++++++++++++++ src/Model/WorkspaceAccountStats.php | 40 ++++++++++++++++++++++++ src/Model/WorkspaceAnalytics.php | 34 ++++++++++++++++++++ src/Resource/AccountsResource.php | 33 ++++++++++++++++++++ src/Resource/WorkspacesResource.php | 7 +++++ tests/AccountsTest.php | 43 +++++++++++++++++++++++++ tests/WorkspacesTest.php | 16 ++++++++++ 11 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 src/Model/AccountAnalyticsHistory.php create mode 100644 src/Model/AccountPrimary.php create mode 100644 src/Model/AccountSnapshot.php create mode 100644 src/Model/AccountValidation.php create mode 100644 src/Model/WorkspaceAccountStats.php create mode 100644 src/Model/WorkspaceAnalytics.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 6869507..67c04fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,11 @@ All notable changes to `fopost/sdk` are documented here. (`listRuns`, `getRun`), with `Automation`, `AutomationStep`, `AutomationStats`, `AutomationVersion`, `AutomationNodeRef`, `AutomationRestore`, `AutomationRun`, `AutomationRunLog` and `AutomationToggle`. -- `$client->workspaces()->create()`, `update()` and `delete()`. `Workspace` carries +- `$client->workspaces()->create()`, `update()`, `delete()` and `analytics()` (`WorkspaceAnalytics`, + `WorkspaceAccountStats`). `Workspace` carries `connectRedirectDomains` and `updatedAt`. +- `$client->accounts()->validate()` (`AccountValidation`), `refreshToken()`, `togglePrimary()` + (`AccountPrimary`) and `analyticsHistory()` (`AccountAnalyticsHistory`, `AccountSnapshot`). - `$client->accounts()` X communities: `listCommunities`, `syncCommunities`, `searchCommunities`, `addCommunity` and `removeCommunity` (`XCommunity`, `XCommunityMatch`). - `$client->logs()->list()` reads the request log into `RequestLogPage` (`RequestLog`, diff --git a/src/Model/AccountAnalyticsHistory.php b/src/Model/AccountAnalyticsHistory.php new file mode 100644 index 0000000..3d83c5b --- /dev/null +++ b/src/Model/AccountAnalyticsHistory.php @@ -0,0 +1,33 @@ + $history */ + private function __construct( + array $raw, + public readonly string $accountId, + public readonly string $platform, + public readonly string $username, + public readonly array $history, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'account_id'), + self::requiredStr($data, 'platform'), + self::requiredStr($data, 'username'), + AccountSnapshot::listFrom(self::seq($data, 'history')), + ); + } +} diff --git a/src/Model/AccountPrimary.php b/src/Model/AccountPrimary.php new file mode 100644 index 0000000..6770d40 --- /dev/null +++ b/src/Model/AccountPrimary.php @@ -0,0 +1,21 @@ + $accounts */ + private function __construct( + array $raw, + public readonly string $workspaceId, + public readonly array $accounts, + public readonly int $totalFollowers, + public readonly int $totalPosts, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + $totals = self::map($data, 'totals'); + + return new self( + $data, + self::requiredStr($data, 'workspace_id'), + WorkspaceAccountStats::listFrom(self::seq($data, 'accounts')), + self::int($totals, 'followers') ?? 0, + self::int($totals, 'total_posts') ?? 0, + ); + } +} diff --git a/src/Resource/AccountsResource.php b/src/Resource/AccountsResource.php index d4406d2..93831fa 100644 --- a/src/Resource/AccountsResource.php +++ b/src/Resource/AccountsResource.php @@ -4,9 +4,12 @@ namespace Fopost\Sdk\Resource; +use Fopost\Sdk\Model\AccountAnalyticsHistory; use Fopost\Sdk\Model\AccountMove; +use Fopost\Sdk\Model\AccountPrimary; use Fopost\Sdk\Model\AccountPlatformMetrics; use Fopost\Sdk\Model\AccountRename; +use Fopost\Sdk\Model\AccountValidation; use Fopost\Sdk\Model\DiscordChannel; use Fopost\Sdk\Model\DiscordIdentity; use Fopost\Sdk\Model\DiscordMember; @@ -39,6 +42,7 @@ use Fopost\Sdk\Model\TelegramBotCommands; use Fopost\Sdk\Model\TelegramConnectCode; use Fopost\Sdk\Model\TelegramConnectStatus; +use DateTimeImmutable; use Fopost\Sdk\Model\WebhookSubscription; use Fopost\Sdk\Model\XCommunity; use Fopost\Sdk\Model\XCommunityMatch; @@ -109,6 +113,35 @@ public function platformMetrics(string $accountId): AccountPlatformMetrics ); } + /** Check the stored credentials against the network now. */ + public function validate(string $accountId): AccountValidation + { + return AccountValidation::fromArray(self::unwrap($this->http->post("/accounts/{$accountId}/validate"))); + } + + /** Refresh the access token now; answers when the new one expires, or null when it does not. */ + public function refreshToken(string $accountId): ?DateTimeImmutable + { + $body = self::asArray(self::unwrap($this->http->post("/accounts/{$accountId}/refresh-token"))); + $expiresAt = $body['expires_at'] ?? null; + + return is_string($expiresAt) && $expiresAt !== '' ? new DateTimeImmutable($expiresAt) : null; + } + + /** Make the account the workspace's primary one, or step it down when it already is. */ + public function togglePrimary(string $accountId): AccountPrimary + { + return AccountPrimary::fromArray(self::unwrap($this->http->post("/accounts/{$accountId}/primary"))); + } + + /** The collected profile readings, newest first; `$limit` caps how many. */ + public function analyticsHistory(string $accountId, ?int $limit = null): AccountAnalyticsHistory + { + $body = $this->http->get("/accounts/{$accountId}/analytics", self::compact(['limit' => $limit])); + + return AccountAnalyticsHistory::fromArray(self::unwrap($body)); + } + /** Rename the account; null or an empty string restores the platform name. */ public function update(string $accountId, ?string $displayName): AccountRename { diff --git a/src/Resource/WorkspacesResource.php b/src/Resource/WorkspacesResource.php index 7bc7897..c68831f 100644 --- a/src/Resource/WorkspacesResource.php +++ b/src/Resource/WorkspacesResource.php @@ -5,6 +5,7 @@ namespace Fopost\Sdk\Resource; use Fopost\Sdk\Model\Workspace; +use Fopost\Sdk\Model\WorkspaceAnalytics; use Fopost\Sdk\Undefined; /** $client->workspaces(): the workspaces the key can reach. */ @@ -21,6 +22,12 @@ public function get(string $workspaceId): Workspace return Workspace::fromArray(self::unwrap($this->http->get("/workspaces/{$workspaceId}"))); } + /** The latest profile numbers of every account in the workspace, and their sum. */ + public function analytics(string $workspaceId): WorkspaceAnalytics + { + return WorkspaceAnalytics::fromArray(self::unwrap($this->http->get("/workspaces/{$workspaceId}/analytics"))); + } + /** `$type` is PERSONAL, TEAM, ORGANIZATION, CLIENT, PROJECT, DEPARTMENT, EVENT, TEMPORARY, COMMUNITY, BRAND or AGENCY. */ public function create( string $name, diff --git a/tests/AccountsTest.php b/tests/AccountsTest.php index 0e00d24..23c2cde 100644 --- a/tests/AccountsTest.php +++ b/tests/AccountsTest.php @@ -459,4 +459,47 @@ public function testInstagramAndLinkedInReads(): void $mentions = $this->client()->accounts()->searchLinkedInMentions('a_1', 'devtestco'); $this->assertStringEndsWith('(urn:li:organization:2414183)', $mentions[0]->annotation); } + + public function testValidateRefreshPrimaryAndHistoryReachTheAccount(): void + { + $this->transport->push(200, [ + 'account_id' => 'a_1', + 'platform' => 'bluesky', + 'valid' => true, + 'health_status' => 'healthy', + 'username' => 'yourbrand', + ]); + $this->transport->push(200, ['expires_at' => '2026-04-01T09:00:00Z']); + $this->transport->push(200, ['id' => 'a_1', 'is_primary' => true]); + $this->transport->push(200, [ + 'account_id' => 'a_1', + 'platform' => 'bluesky', + 'username' => 'yourbrand', + 'history' => [['followers' => 200, 'reach' => 50, 'fetched_at' => '2026-03-01T09:00:00Z']], + ]); + + $accounts = $this->client()->accounts(); + $validation = $accounts->validate('a_1'); + $expiresAt = $accounts->refreshToken('a_1'); + $primary = $accounts->togglePrimary('a_1'); + $history = $accounts->analyticsHistory('a_1', 30); + + $this->assertSame('POST', $this->transport->requests[0]['method']); + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/validate', $this->transport->requests[0]['url']); + $this->assertTrue($validation->valid); + $this->assertSame('healthy', $validation->healthStatus); + + $this->assertSame('POST', $this->transport->requests[1]['method']); + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/refresh-token', $this->transport->requests[1]['url']); + $this->assertSame('2026-04-01', $expiresAt?->format('Y-m-d')); + + $this->assertSame('POST', $this->transport->requests[2]['method']); + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/primary', $this->transport->requests[2]['url']); + $this->assertTrue($primary->isPrimary); + + $this->assertSame('GET', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/accounts/a_1/analytics?limit=30', $this->transport->last()['url']); + $this->assertSame(200, $history->history[0]->followers); + $this->assertSame(50, $history->history[0]->reach); + } } diff --git a/tests/WorkspacesTest.php b/tests/WorkspacesTest.php index 1c48fde..a9e5ce3 100644 --- a/tests/WorkspacesTest.php +++ b/tests/WorkspacesTest.php @@ -75,4 +75,20 @@ public function testCreateUpdateAndDeleteSendTheRightBodies(): void $this->assertSame('DELETE', $this->transport->last()['method']); $this->assertSame('https://api.fopost.com/v1/workspaces/w_2', $this->transport->last()['url']); } + + public function testAnalyticsSumsTheAccounts(): void + { + $this->transport->push(200, [ + 'workspace_id' => 'w_1', + 'accounts' => [['account_id' => 'a_1', 'platform' => 'bluesky', 'username' => 'y', 'followers' => 200]], + 'totals' => ['followers' => 200, 'total_posts' => 12], + ]); + + $analytics = $this->client()->workspaces()->analytics('w_1'); + + $this->assertSame('GET', $this->transport->last()['method']); + $this->assertSame('https://api.fopost.com/v1/workspaces/w_1/analytics', $this->transport->last()['url']); + $this->assertSame(200, $analytics->accounts[0]->followers); + $this->assertSame(12, $analytics->totalPosts); + } }