Skip to content

Open source alternative to Semrush and Ahrefs

Match DataForSEO pricing for SERP keywords with search operators (#695)

Carter Smith0b6bfbf8b713
diff --git a/src/client/features/rank-tracking/CheckConfirmModal.tsx b/src/client/features/rank-tracking/CheckConfirmModal.tsx
index aefc1e3d..09480a17 100644
--- a/src/client/features/rank-tracking/CheckConfirmModal.tsx
+++ b/src/client/features/rank-tracking/CheckConfirmModal.tsx
@@ -2,7 +2,6 @@ import { Loader2, Zap } from "lucide-react";
import { Modal } from "@/client/components/Modal";
import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
import {
- estimateRankCheckCredits,
devicesCount,
KEYWORDS_PER_BATCH,
SECONDS_PER_BATCH,
@@ -11,24 +10,19 @@ import {
export function CheckConfirmModal({
keywordCount,
devices,
- serpDepth,
+ costUsd,
isPending,
onRunNow,
onCancel,
}: {
keywordCount: number;
devices: RankTrackingConfig["devices"];
- serpDepth: number;
+ /** Server estimate; it prices each keyword's text (operators cost 5x). */
+ costUsd: number | undefined;
isPending: boolean;
onRunNow: () => void;
onCancel: () => void;
}) {
- const { costUsd } = estimateRankCheckCredits(
- keywordCount,
- devices,
- serpDepth,
- "live",
- );
const dc = devicesCount(devices);
const totalChecks = keywordCount * dc;
const liveTime =
@@ -67,7 +61,9 @@ export function CheckConfirmModal({
</p>
</div>
<div className="text-right">
- <p className="font-mono font-semibold">~${costUsd.toFixed(2)}</p>
+ {costUsd != null && (
+ <p className="font-mono font-semibold">~${costUsd.toFixed(2)}</p>
+ )}
{isPending && <Loader2 className="size-3 animate-spin ml-auto" />}
</div>
</button>
diff --git a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
index f242a5bc..1316212c 100644
--- a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
+++ b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
@@ -365,7 +365,7 @@ function RankTrackingConfigModalContent({
// Scheduled checks run through the cheaper task queue; manual
// configs only ever pay the live price.
const { costUsd: costPerKeyword } = estimateRankCheckCredits(
- 1,
+ ["plain keyword"],
devices,
serpDepth,
schedule === "manual" ? "live" : "queued",
diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
index 139861b0..0fcc4dfc 100644
--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx
@@ -355,7 +355,7 @@ export function RankTrackingDomainDetail({
<CheckConfirmModal
keywordCount={pendingCheck.count}
devices={config.devices}
- serpDepth={config.serpDepth}
+ costUsd={costEstimate?.costUsd}
isPending={isPending}
onRunNow={() =>
startCheck({
diff --git a/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts b/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
index 35682773..d280459f 100644
--- a/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
+++ b/src/server/features/rank-tracking/repositories/RankTrackingRepository.ts
@@ -344,14 +344,6 @@ async function updateKeywordMetrics(
);
}
-async function getKeywordCountForConfig(configId: string) {
- const rows = await db
- .select({ value: count() })
- .from(rankTrackingKeywords)
- .where(eq(rankTrackingKeywords.configId, configId));
- return rows[0]?.value ?? 0;
-}
-
/** Keyword counts keyed by config id. Configs with no keywords are absent. */
async function getKeywordCountsForConfigs(configIds: string[]) {
// Chunked so the IN list stays under D1's ~100 bound-parameter cap.
@@ -388,7 +380,6 @@ export const RankTrackingRepository = {
addKeywordsToConfig,
removeKeywordsFromConfig,
updateKeywordMetrics,
- getKeywordCountForConfig,
getKeywordCountsForConfigs,
getConfigSummaries,
getLatestSnapshotsForKeywords,
diff --git a/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts b/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
index d60d321c..9e1a2c89 100644
--- a/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingKeywordService.ts
@@ -67,7 +67,7 @@ async function addKeywords(
| undefined;
if (rows.length > 0 && scheduleInterval) {
scheduledEstimate = estimateScheduledRankCheckCredits(
- existing.length + rows.length,
+ [...existing, ...rows].map((kw) => kw.keyword),
config.devices,
config.serpDepth,
scheduleInterval,
@@ -93,10 +93,10 @@ async function addKeywords(
addedIds.length > 0 &&
approval.kind === "credit_ceiling"
) {
- const persistedKeywordCount =
- await RankTrackingRepository.getKeywordCountForConfig(configId);
+ const persisted =
+ await RankTrackingRepository.getKeywordsForConfig(configId);
scheduledEstimate = estimateScheduledRankCheckCredits(
- persistedKeywordCount,
+ persisted.map((kw) => kw.keyword),
config.devices,
config.serpDepth,
scheduleInterval,
@@ -130,20 +130,18 @@ async function removeKeywords(
async function estimateCost(
configId: string,
projectId: string,
- additionalKeywordCount = 0,
+ additionalKeywords: readonly string[] = [],
) {
const config = await getValidatedConfig(configId, projectId);
- const existingKeywordCount =
- await RankTrackingRepository.getKeywordCountForConfig(configId);
- const keywordCount = Math.max(
- existingKeywordCount,
- Math.min(
- MAX_KEYWORDS_PER_CONFIG,
- existingKeywordCount + additionalKeywordCount,
- ),
- );
+ const existing = await RankTrackingRepository.getKeywordsForConfig(configId);
+ const existingKeywordCount = existing.length;
+ const keywords = [
+ ...existing.map((kw) => kw.keyword),
+ ...additionalKeywords,
+ ].slice(0, Math.max(existingKeywordCount, MAX_KEYWORDS_PER_CONFIG));
+ const keywordCount = keywords.length;
const { costUsd, costCredits } = estimateRankCheckCredits(
- keywordCount,
+ keywords,
config.devices,
config.serpDepth,
"live",
@@ -164,7 +162,7 @@ async function estimateCost(
additionalKeywordCount: keywordCount - existingKeywordCount,
scheduledEstimate: scheduleInterval
? estimateScheduledRankCheckCredits(
- keywordCount,
+ keywords,
config.devices,
config.serpDepth,
scheduleInterval,
@@ -190,7 +188,7 @@ function scheduledApprovalError(
) {
return new AppError(
"VALIDATION_ERROR",
- `Adding these keywords would make each ${scheduleInterval} scheduled check cost a nominal queued estimate of ${estimate.costCredits} credits (~$${estimate.costUsd.toFixed(4)} per check; ~${estimate.monthlyCostCredits} credits/month). Call estimate_rank_tracker_cost with additionalKeywordCount, show the recurring estimate and live-fallback caveat to the user, then retry with maxEstimatedScheduledCheckCredits set to the approved per-check estimate. Live fallback for rejected, failed, or timed-out queued tasks may use additional separately billed credits.`,
+ `Adding these keywords would make each ${scheduleInterval} scheduled check cost a nominal queued estimate of ${estimate.costCredits} credits (~$${estimate.costUsd.toFixed(4)} per check; ~${estimate.monthlyCostCredits} credits/month). Call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate and live-fallback caveat to the user, then retry with maxEstimatedScheduledCheckCredits set to the approved per-check estimate. Live fallback for rejected, failed, or timed-out queued tasks may use additional separately billed credits.`,
);
}
diff --git a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts b/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
index 781e884d..382eea4b 100644
--- a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts
@@ -6,7 +6,6 @@ const mocks = vi.hoisted(() => ({
getKeywordsForConfig: vi.fn(),
addKeywordsToConfig: vi.fn(),
removeKeywordsFromConfig: vi.fn(),
- getKeywordCountForConfig: vi.fn(),
updateKeywordMetrics: vi.fn(),
isHostedServerAuthMode: vi.fn(),
customerHasPaidPlan: vi.fn(),
@@ -127,8 +126,12 @@ describe("RankTrackingService management invariants", () => {
});
it("adds scheduled keywords at the approved estimate", async () => {
- mocks.getKeywordsForConfig.mockResolvedValue([]);
- mocks.getKeywordCountForConfig.mockResolvedValue(2);
+ mocks.getKeywordsForConfig
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([
+ { keyword: "seo" },
+ { keyword: "technical seo" },
+ ]);
mocks.addKeywordsToConfig.mockImplementation(
async (rows: Array<{ id: string }>) => rows.map((row) => row.id),
);
@@ -155,8 +158,13 @@ describe("RankTrackingService management invariants", () => {
});
it("rolls back its inserts when a concurrent add exceeds the estimate", async () => {
- mocks.getKeywordsForConfig.mockResolvedValue([]);
- mocks.getKeywordCountForConfig.mockResolvedValue(3);
+ mocks.getKeywordsForConfig
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([
+ { keyword: "seo" },
+ { keyword: "technical seo" },
+ { keyword: "concurrent add" },
+ ]);
mocks.addKeywordsToConfig.mockImplementation(
async (rows: Array<{ id: string }>) => rows.map((row) => row.id),
);
@@ -197,7 +205,7 @@ describe("RankTrackingService management invariants", () => {
kind: "credit_ceiling",
}),
).resolves.toMatchObject({ added: 1, scheduledEstimate: undefined });
- expect(mocks.getKeywordCountForConfig).not.toHaveBeenCalled();
+ expect(mocks.getKeywordsForConfig).toHaveBeenCalledTimes(1);
});
it("rejects a hosted unpaid run before keyword or workflow work", async () => {
diff --git a/src/server/features/rank-tracking/services/RankTrackingService.ts b/src/server/features/rank-tracking/services/RankTrackingService.ts
index 8e39bd26..1fa21e68 100644
--- a/src/server/features/rank-tracking/services/RankTrackingService.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingService.ts
@@ -265,7 +265,7 @@ async function triggerCheck(input: {
if (input.maxCostCredits != null) {
const { costCredits } = estimateRankCheckCredits(
- keywords.length,
+ keywords.map((kw) => kw.keyword),
config.devices,
config.serpDepth,
"live",
diff --git a/src/server/lib/dataforseo/pricing.test.ts b/src/server/lib/dataforseo/pricing.test.ts
index 8ea7db34..52dceeec 100644
--- a/src/server/lib/dataforseo/pricing.test.ts
+++ b/src/server/lib/dataforseo/pricing.test.ts
@@ -34,6 +34,15 @@ describe("dataforseoPricing", () => {
rawUsd: 0.0035,
credits: 5,
},
+ {
+ name: "live SERP for a keyword with a search operator (billed 5x)",
+ estimateUsd: dataforseoPricing.serp.live({
+ keyword: "site:example.com seo",
+ ...location,
+ }),
+ rawUsd: 0.0175,
+ credits: 23,
+ },
{
name: "Lighthouse run",
estimateUsd: dataforseoPricing.lighthouse.live({
@@ -127,19 +136,37 @@ describe("dataforseoPricing", () => {
);
it("prices a queued task_post batch the way the rank check estimate does", () => {
- const tasks = Array.from({ length: 100 }, (_, i) => ({
- keyword: `kw ${i}`,
- keywordId: `id-${i}`,
- device: "desktop" as const,
- }));
+ // Operator keywords bill 5x, so approvals must see the same mix.
+ const keywords = Array.from({ length: 100 }, (_, i) =>
+ i % 10 === 0 ? `site:example.com kw ${i}` : `kw ${i}`,
+ );
const estimateUsd = dataforseoPricing.serp.rankCheckTaskPost({
- tasks,
+ tasks: keywords.map((keyword, i) => ({
+ keyword,
+ keywordId: `id-${i}`,
+ device: "desktop" as const,
+ })),
+ ...location,
+ depth: 20,
+ targetDomain: "example.com",
+ });
+ expect(creditsForProviderUsd(estimateUsd)).toBe(
+ estimateRankCheckCredits(keywords, "desktop", 20, "queued").costCredits,
+ );
+ });
+
+ it("prices a live operator rank check the way the rank check estimate does", () => {
+ const keyword = "site:example.com seo";
+ const estimateUsd = dataforseoPricing.serp.rankCheck({
+ keyword,
+ keywordId: "id",
...location,
+ device: "desktop",
depth: 20,
targetDomain: "example.com",
});
expect(creditsForProviderUsd(estimateUsd)).toBe(
- estimateRankCheckCredits(100, "desktop", 20, "queued").costCredits,
+ estimateRankCheckCredits([keyword], "desktop", 20, "live").costCredits,
);
});
});
diff --git a/src/server/lib/dataforseo/pricing.ts b/src/server/lib/dataforseo/pricing.ts
index 546ba40b..e1afb46e 100644
--- a/src/server/lib/dataforseo/pricing.ts
+++ b/src/server/lib/dataforseo/pricing.ts
@@ -46,7 +46,10 @@ import {
type LlmResponseModelSlug,
resolveLlmMentionsLimit,
} from "@/server/lib/dataforseo/ai";
-import { costPerSerpAtDepth } from "@/shared/rank-tracking";
+import {
+ costPerSerpAtDepth,
+ serpKeywordCostMultiplier,
+} from "@/shared/rank-tracking";
/**
* Raw DataForSEO USD upper bound for one metered call, computed from the
@@ -148,8 +151,11 @@ function backlinksUsd(rows: number) {
}
/** SERP endpoints bill per page of 10; a partial page is a full page. */
-function serpUsd(depth: number, method: "live" | "queued") {
- return costPerSerpAtDepth(Math.ceil(depth / 10) * 10, method);
+function serpUsd(depth: number, method: "live" | "queued", keyword: string) {
+ return (
+ costPerSerpAtDepth(Math.ceil(depth / 10) * 10, method) *
+ serpKeywordCostMultiplier(keyword)
+ );
}
function daysInclusive(from: string, to: string) {
@@ -226,15 +232,21 @@ export const dataforseoPricing = {
},
serp: {
live: priced(fetchLiveSerp, (input) =>
- serpUsd(clampSerpDepth(input.depth ?? SERP_ANALYSIS_DEPTH), "live"),
+ serpUsd(
+ clampSerpDepth(input.depth ?? SERP_ANALYSIS_DEPTH),
+ "live",
+ input.keyword,
+ ),
),
rankCheck: priced(fetchRankCheckSerp, (input) =>
- serpUsd(clampSerpDepth(input.depth), "live"),
+ serpUsd(clampSerpDepth(input.depth), "live", input.keyword),
),
- rankCheckTaskPost: priced(
- postRankCheckTasks,
- (input) =>
- input.tasks.length * serpUsd(clampSerpDepth(input.depth), "queued"),
+ rankCheckTaskPost: priced(postRankCheckTasks, (input) =>
+ input.tasks.reduce(
+ (sum, task) =>
+ sum + serpUsd(clampSerpDepth(input.depth), "queued", task.keyword),
+ 0,
+ ),
),
local: priced(fetchLocalSerp, (input) =>
input.searchType === "maps"
diff --git a/src/server/mcp/tools/add-rank-tracking-keywords.ts b/src/server/mcp/tools/add-rank-tracking-keywords.ts
index f5525c6c..743d8a8c 100644
--- a/src/server/mcp/tools/add-rank-tracking-keywords.ts
+++ b/src/server/mcp/tools/add-rank-tracking-keywords.ts
@@ -30,7 +30,7 @@ const inputSchema = {
.positive()
.optional()
.describe(
- "Nominal queued credits per scheduled check that the user approved after seeing estimate_rank_tracker_cost with additionalKeywordCount. Required for scheduled trackers. This is an estimate approval, not a runtime cap; live fallback may add separately billed credits.",
+ "Nominal queued credits per scheduled check that the user approved after seeing estimate_rank_tracker_cost with additionalKeywords. Required for scheduled trackers. This is an estimate approval, not a runtime cap; live fallback may add separately billed credits.",
),
} as const;
@@ -41,7 +41,7 @@ export const addRankTrackingKeywordsTool = {
config: {
title: "Add rank tracking keywords",
description:
- "Add keywords to an existing rank tracker. The mutation itself uses no credits and does not start a check or fetch metrics, but scheduled trackers will spend credits on future recurring checks. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywordCount, show the recurring estimate and live-fallback caveat to the user, and pass the approved nominal per-check estimate as maxEstimatedScheduledCheckCredits. This approval is not a runtime spending cap: rejected, failed, or timed-out queued tasks may use additional separately billed live fallback. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",
+ "Add keywords to an existing rank tracker. The mutation itself uses no credits and does not start a check or fetch metrics, but scheduled trackers will spend credits on future recurring checks. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate and live-fallback caveat to the user, and pass the approved nominal per-check estimate as maxEstimatedScheduledCheckCredits. This approval is not a runtime spending cap: rejected, failed, or timed-out queued tasks may use additional separately billed live fallback. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",
inputSchema,
outputSchema: z
.object({
diff --git a/src/server/mcp/tools/estimate-rank-tracker-cost.ts b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
index b1d33caa..376d3932 100644
--- a/src/server/mcp/tools/estimate-rank-tracker-cost.ts
+++ b/src/server/mcp/tools/estimate-rank-tracker-cost.ts
@@ -19,7 +19,14 @@ const inputSchema = {
.max(1000)
.optional()
.describe(
- "Number of keywords you plan to add. Include this before adding to a scheduled tracker so the response projects its recurring per-check and monthly cost.",
+ "Number of keywords you plan to add, priced as plain keywords. Prefer additionalKeywords when you know them.",
+ ),
+ additionalKeywords: z
+ .array(z.string())
+ .max(1000)
+ .optional()
+ .describe(
+ "Keywords you plan to add. Include these before adding to a scheduled tracker so the response projects its recurring per-check and monthly cost; keywords with search operators such as site: cost 5x. Overrides additionalKeywordCount.",
),
} as const;
@@ -30,7 +37,7 @@ export const estimateRankTrackerCostTool = {
config: {
title: "Estimate rank tracker cost",
description:
- "Estimate rank tracker cost without spending credits or starting a check. The live estimate covers one explicit run_rank_tracker check. For a scheduled tracker, the response also includes nominal queued per-check and approximate monthly recurring cost. Pass additionalKeywordCount before adding keywords to project the post-add cost. Scheduled estimates are not runtime caps; rejected, failed, or timed-out queued tasks may use additional separately billed live fallback.",
+ "Estimate rank tracker cost without spending credits or starting a check. The live estimate covers one explicit run_rank_tracker check. For a scheduled tracker, the response also includes nominal queued per-check and approximate monthly recurring cost. Pass additionalKeywords before adding keywords to project the post-add cost. Scheduled estimates are not runtime caps; rejected, failed, or timed-out queued tasks may use additional separately billed live fallback.",
inputSchema,
outputSchema: z
.object({
@@ -66,7 +73,9 @@ export const estimateRankTrackerCostTool = {
const estimate = await RankTrackingService.estimateCost(
args.trackerId,
args.projectId,
- args.additionalKeywordCount,
+ // A bare count has no keyword text, so it prices as plain keywords.
+ args.additionalKeywords ??
+ Array<string>(args.additionalKeywordCount ?? 0).fill(""),
);
return mcpResponse({
text: `One live check for tracker ${args.trackerId} is estimated at $${estimate.costUsd.toFixed(4)} (${estimate.costCredits} credits): ${estimate.keywordCount} keyword${estimate.keywordCount === 1 ? "" : "s"} × ${estimate.devicesCount} device${estimate.devicesCount === 1 ? "" : "s"} = ${estimate.totalChecks} SERP checks.${estimate.additionalKeywordCount > 0 ? ` This projects ${estimate.additionalKeywordCount} additional keyword${estimate.additionalKeywordCount === 1 ? "" : "s"}.` : ""}${estimate.scheduledEstimate ? ` Its ${estimate.scheduledEstimate.scheduleInterval} queued checks have a nominal estimate of $${estimate.scheduledEstimate.costUsd.toFixed(4)} (${estimate.scheduledEstimate.costCredits} credits) each, or about $${estimate.scheduledEstimate.monthlyCostUsd.toFixed(4)} (${estimate.scheduledEstimate.monthlyCostCredits} credits) per month. Show the user that rejected, failed, or timed-out queued tasks may use additional separately billed live fallback, then use the per-check estimate as maxEstimatedScheduledCheckCredits when adding keywords.` : ""} No check was started.`,
diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.ts
index 9abe7647..c0f2cdc9 100644
--- a/src/server/workflows/RankCheckWorkflow.ts
+++ b/src/server/workflows/RankCheckWorkflow.ts
@@ -86,7 +86,7 @@ async function prepareRankCheckKeywords(input: {
}
const { costCredits } = estimateRankCheckCredits(
- trackingKeywords.length,
+ trackingKeywords.map((kw) => kw.keyword),
input.devices,
input.serpDepth,
input.trigger === "scheduled" ? "queued" : "live",
diff --git a/src/shared/rank-tracking.test.ts b/src/shared/rank-tracking.test.ts
index 549a188e..8084a659 100644
--- a/src/shared/rank-tracking.test.ts
+++ b/src/shared/rank-tracking.test.ts
@@ -39,7 +39,12 @@ describe("rank tracking cost estimates", () => {
"matches per-call billing for $method checks",
({ keywordCount, devices, depth, method, costUsd, costCredits }) => {
expect(
- estimateRankCheckCredits(keywordCount, devices, depth, method),
+ estimateRankCheckCredits(
+ Array.from({ length: keywordCount }, (_, i) => `kw ${i}`),
+ devices,
+ depth,
+ method,
+ ),
).toEqual({ costUsd, costCredits });
},
);
diff --git a/src/shared/rank-tracking.ts b/src/shared/rank-tracking.ts
index af49eb9f..bcd06688 100644
--- a/src/shared/rank-tracking.ts
+++ b/src/shared/rank-tracking.ts
@@ -78,13 +78,29 @@ export function pagesToDepth(pages: number): number {
return pages * 10;
}
+// Google Organic bills 5x when the keyword contains an advanced search
+// operator (docs.dataforseo.com/v3/serp/google/organic/live/advanced). The
+// docs say "contains", so match anywhere: a false match only over-holds.
+const SERP_OPERATOR_KEYWORD =
+ /(allinanchor|allintext|allintitle|allinurl|cache|define|definition|filetype|id|inanchor|info|intext|intitle|inurl|link|site):/i;
+
+export function serpKeywordCostMultiplier(keyword: string) {
+ return SERP_OPERATOR_KEYWORD.test(keyword) ? 5 : 1;
+}
+
export function estimateRankCheckCredits(
- keywordCount: number,
+ keywords: readonly string[],
devices: RankTrackingConfig["devices"],
depth: number,
method: RankCheckMethod,
) {
- const totalChecks = keywordCount * devicesCount(devices);
+ // One entry per keyword/device pair, keyword-major like the workflow's
+ // task list, so queued chunks group the same pairs the real posts do.
+ const checkMultipliers = keywords.flatMap((keyword) =>
+ Array<number>(devicesCount(devices)).fill(
+ serpKeywordCostMultiplier(keyword),
+ ),
+ );
const checksPerMeteredCall = method === "queued" ? MAX_TASKS_PER_POST : 1;
let costUsd = 0;
let costCredits = 0;
@@ -93,9 +109,15 @@ export function estimateRankCheckCredits(
// checks make one call per keyword/device pair, while queued checks post up
// to MAX_TASKS_PER_POST pairs per call. Summing one aggregate and rounding
// once can therefore understate the credits that will actually be charged.
- for (let offset = 0; offset < totalChecks; offset += checksPerMeteredCall) {
- const checksInCall = Math.min(checksPerMeteredCall, totalChecks - offset);
- const callRawUsd = checksInCall * costPerSerpAtDepth(depth, method);
+ for (
+ let offset = 0;
+ offset < checkMultipliers.length;
+ offset += checksPerMeteredCall
+ ) {
+ const callMultiplier = checkMultipliers
+ .slice(offset, offset + checksPerMeteredCall)
+ .reduce((sum, multiplier) => sum + multiplier, 0);
+ const callRawUsd = callMultiplier * costPerSerpAtDepth(depth, method);
costUsd += applyBillingMarkupUsd(callRawUsd);
costCredits += creditsForProviderUsd(callRawUsd);
}
@@ -123,13 +145,13 @@ export type RankTrackingSkipReason =
| "insufficient_credits";
export function estimateScheduledRankCheckCredits(
- keywordCount: number,
+ keywords: readonly string[],
devices: RankTrackingConfig["devices"],
depth: number,
scheduleInterval: ScheduledRankTrackingInterval,
) {
const { costUsd, costCredits } = estimateRankCheckCredits(
- keywordCount,
+ keywords,
devices,
depth,
"queued",