<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexandre Kuzo on Medium]]></title>
        <description><![CDATA[Stories by Alexandre Kuzo on Medium]]></description>
        <link>https://medium.com/@alexandre.kuzo_66025?source=rss-92b6fe7a5930------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZgE2Pek2tK3lTVM7</url>
            <title>Stories by Alexandre Kuzo on Medium</title>
            <link>https://medium.com/@alexandre.kuzo_66025?source=rss-92b6fe7a5930------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:26:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexandre.kuzo_66025/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Built an AI SDR Agent with Clay, LangGraph, Slack and Salesforce]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/built-an-ai-sdr-agent-with-clay-langgraph-slack-and-salesforce-623793c93584?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/623793c93584</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[gtm-engineering]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 11:49:53 GMT</pubDate>
            <atom:updated>2026-11-13T11:49:53.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Rq-Wrr7BHjhDOXNHrT46pQ.png" /></figure><p><em>A lead qualification POC where AI does the prep work and the SDR keeps the decision, one click away in Slack.</em></p><p>As far as I know, SDRs spend a good part of the day on tasks that are not selling: checking whether a lead already exists in the CRM, judging whether it deserves an email, writing that email, then re-entering everything in Salesforce. Enrichment tools like Clay have solved data collection. What about after?</p><p>I wanted to see how far an agent could automate that sequence without taking over the part that should stay human: the choice to contact someone or not. The result is an open source proof of concept, which I demo on video across three real scenarios (in French, activate subtitles if needed).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fpx2YKSwgvyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dpx2YKSwgvyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fpx2YKSwgvyA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a06766f3e784c1f908f30be10a3f8cb/href">https://medium.com/media/8a06766f3e784c1f908f30be10a3f8cb/href</a></iframe><p>This article covers what the agent does, the technical choices behind it, and what it still lacks before going to production.</p><h3><strong>What the agent does</strong></h3><p>The agent takes a lead enriched by Clay and carries it to Salesforce in six steps, with a mandatory stop in front of a human.</p><ol><li><strong>Intake.</strong> Clay sends the enriched lead (company, domain, decision maker’s email and role, company size) to a webhook protected by a shared secret.</li><li><strong>Deduplication.</strong> The agent searches Salesforce for an existing lead on the same domain.</li><li><strong>ICP scoring.</strong> It assigns a score from 0 to 100 with a rationale, using an LLM, or a simple rule when no API key is configured.</li><li><strong>Drafting and notification.</strong> If the lead is new, scores 50 or more, and has a decision maker, the agent drafts an outreach email and posts it to Slack with the score, its reasoning and two buttons: Approve and Reject.</li><li><strong>Pause.</strong> The workflow stops and waits. Nothing moves until someone clicks.</li><li><strong>Follow-through.</strong> On Approve, the agent prepares a draft in the SDR’s Gmail inbox, creates the lead in Salesforce and attaches a task containing the email. On Reject, it does nothing.</li></ol><p>Two rules hold the whole thing together: no irreversible action without human approval, and the agent never sends an email itself. It prepares a draft, and the SDR stays in control of sending.</p><h3><strong>The three demo scenarios</strong></h3><p>The video walks through the three possible outcomes, on a test Clay table and a Salesforce developer org.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*VrvcsGLe8o-m583xt2mWHQ.png" /></figure><p>Scenario B is interesting: a “good” SDR agent is also judged by what it does not show: an off-target lead should not waste time of the selling teams.</p><p>Scenario C matters just as much. A lead can tick every box and still be the wrong contact, for a reason only the rep knows. Rejecting must therefore be as easy as approving, and leave nothing behind to clean up.</p><h3><strong>LangGraph rather than a no-code tool or Agentforce</strong></h3><p>I wanted a stack that is open, readable and testable. The workflow fits in a Python file: seven nodes, two conditional routers, one interruption point. Each step is a function I can test on its own, and the project ships with 45 tests that run offline, without any API key.</p><p>Another benefit: the agent depends on no single vendor. Scoring and drafting go through OpenAI or Anthropic depending on which key is provided, and Salesforce is just one client among others, called through its API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvJf6R1E64eqDUzEb08oeQ.png" /><figcaption>Nodes… nodes…</figcaption></figure><h3><strong>A pause that survives a restart</strong></h3><p>This is the part that took the most care. Between the Slack notification and the SDR’s click, ten seconds or two days can go by. The workflow therefore has to stop cleanly, save its state, and resume at exactly the same place.</p><p>LangGraph provides the mechanism “<strong>interrupt_before”</strong>, backed here by a SQLite checkpointer. The state of a lead awaiting approval is written to disk: if the server restarts, nothing is lost. When the SDR clicks, Slack calls a second API route, which injects the decision into the state and resumes the graph.</p><p>One detail required some time to understand: you cannot place the interruption right after the drafting node with a conditional router on it. LangGraph evaluates the router in the same cycle as the node, so before the human decision exists. The fix is an empty pass-through node that serves only as a stopping point.</p><p><strong>Slack as the interface, not one more screen</strong></p><p>The SDR already lives in Slack. Asking them to open another tool to validate leads is a sure way to make sure they never do. The message holds everything needed to decide: the score, the reason for the score, the proposed email, two buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*qVGxrZGtyTv2WKzw9FKcFA.png" /></figure><h3><strong>The limits of this POC</strong></h3><p>This is a proof of concept, and it has the limits of one.</p><ul><li><strong>Test data.</strong> The demo runs on a Clay table in sandbox mode and a Salesforce Developer Edition org, with a handful of rows.</li><li><strong>The Gmail draft is not wired up in the video.</strong> The code exists and is tested, but in the demo the approved email only lands in the Salesforce task.</li><li><strong>A hard-coded ICP.</strong> The threshold of 50 and the scoring criteria live in the code. A real team will want to tune them itself.</li><li><strong>Basic deduplication.</strong> The lookup runs on the company domain, on the Lead object only. It checks neither existing contacts nor accounts.</li><li><strong>Emails that are still generic.</strong> The model only receives the name, size and role. Without richer signals (news, tech stack, funding round), personalization stays limited.</li><li><strong>A single user.</strong> SQLite and a local server exposed through ngrok are enough for a demo, not for a team.</li></ul><h3><strong>What to add for production</strong></h3><p>Four workstreams separate this proof of concept from a tool a sales team would use every day.</p><ol><li><strong>Hosting and persistence.</strong> Replace SQLite with Postgres, deploy the API on a managed service, and process webhooks through a queue to absorb Clay’s bulk sends.</li><li><strong>A configurable ICP.</strong> Move the criteria and the threshold out of the code and store them where Ops can edit them, for example in Salesforce metadata.</li><li><strong>Full routing and deduplication.</strong> Search contacts and accounts as well, then assign the lead to the right SDR by territory, with a targeted notification instead of a shared channel.</li><li><strong>Measurement.</strong> Track approval rate, time to validation and email reply rate. Rejections are valuable data: they show where the scoring gets it wrong.</li></ol><p>None of this calls the architecture into question. The graph stays the same; it is the edges that get hardened.</p><p>The AI part of this project comes down to two model calls: a score and an email. Everything else is integration: a secured webhook, state that persists, an interface where people already work, a CRM that stays clean. That is where the difference lies between an agent demo and a tool a sales rep agrees to use.</p><p>And the principle that makes the whole thing acceptable is simple: the agent proposes, the human decides.</p><p>The code is available here: <a href="https://github.com/AlexandreKuzo/sdr_gtm_ai">github.com/AlexandreKuzo/sdr_gtm_ai</a>.</p><p>If this article helps me to connect with RevOps or GTM Engineering folks, it could be great. Don’t hesitate to share it or reach out 😉</p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=623793c93584" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Duplicate Leads Are a Data Problem. So Why Use an LLM?]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/duplicate-leads-are-a-data-problem-so-why-use-an-llm-ed0d68ee1c70?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0d68ee1c70</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[go-to-market]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 21:29:48 GMT</pubDate>
            <atom:updated>2026-10-28T09:30:13.627Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building a human-in-the-loop Salesforce deduplication workflow with Python and LangGraph.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QR0o5Y8g4rtYCxbqyrE4ww.png" /></figure><p>Duplicate records are a common CRM problem. They can lead to repeated outreach, inconsistent reporting and wasted time for sales teams.</p><p>Finding them sounds simple enough: compare names, emails and phone numbers, then identify the records that match.</p><p>But real-world data is rarely clean like that. Names contain typos, phone numbers use different formats, and some records are missing essential information.</p><p>I built a <a href="https://github.com/AlexandreKuzo/sf_langgraph_dedup_poc">small Python POC</a> to explore this problem using <a href="https://www.langchain.com/langgraph">LangGraph</a>, with Salesforce Leads and Contacts as the target use case.</p><p>The goal wasn’t to build a production-ready deduplication engine. It was to experiment with a structured workflow combining candidate matching, decision-making, human review and enrichment.</p><p>Along the way, I found three bugs that illustrate why reliable automation requires more than a working happy path.</p><h3>1. From candidate matching to human review</h3><p>The workflow separates the problem into several steps:</p><ul><li><strong>Blocking:</strong> group potentially related records to avoid comparing every record against every other record.</li></ul><pre>def blocking_key(contact):<br>    last_name = normalize(contact.get(&quot;last_name&quot;))<br>    first_name = normalize(contact.get(&quot;first_name&quot;))<br><br>    return last_name, first_name[:1]</pre><ul><li><strong>Scoring:</strong> compare names, emails and phone numbers using fuzzy matching.</li><li><strong>Judgment:</strong> classify candidate pairs as duplicates or non-duplicates.</li><li><strong>Human review:</strong> pause the workflow when a decision requires additional scrutiny.</li><li><strong>Next steps:</strong> describe the proposed merge or conversion, enrich surviving records and produce a summary.</li></ul><pre>START -&gt; block_and_match -&gt; judge_pairs -&gt; split_by_confidence<br>                                                   |<br>                                 (conditionnel, route_after_split)<br>                                    /                          \<br>                          human_review                    merge_duplicates<br>                                \                              /<br>                                 -----&gt; merge_duplicates &lt;-----<br>                                              |<br>                                      enrich_contacts -&gt; log_and_monitor -&gt; END</pre><p>LangGraph makes these transitions explicit, including conditional routing and interruption for human input.</p><p>For example, the workflow can pause when a pair requires review, wait for a decision and resume from the interruption point.</p><pre>from langgraph.types import interrupt, Command<br><br>def human_review(state):<br>    decisions = interrupt({<br>        &quot;pairs_to_review&quot;: state[&quot;needs_review&quot;]<br>    })<br><br>    return {&quot;review_decisions&quot;: decisions}</pre><p>In this proof of concept, human review is simulated through the terminal, and the checkpoint is stored in memory.</p><p>The workflow also distinguishes between two different Salesforce scenarios: merging records of the same object type and handling a potential match between a Lead and a Contact, which requires a different process.</p><p>Importantly, the merge step does not modify Salesforce data. It describes the action that would be performed.</p><p>The architecture is experimental, but the separation of responsibilities is useful: finding a candidate, deciding whether it is a duplicate and changing CRM data are three different operations.</p><h3>2. Three bugs that changed the implementation</h3><p>The most useful lessons came from testing edge cases rather than simply checking that the workflow ran.</p><h3>Empty fields produced false positives</h3><p>Python considers two empty strings equal:</p><p>&quot;&quot; == &quot;&quot;</p><p>A fuzzy matching function can also assign a perfect similarity score to two empty strings.</p><p>That is not evidence that two Leads represent the same person.</p><p>When records contain missing information, treating empty fields as ordinary values can inflate their matching scores and produce false positives.</p><p>The fix was to handle missing values explicitly in the scoring logic.</p><p><strong>A similarity function can behave exactly as designed and still produce a bad business decision.</strong></p><h3>Equivalent French phone numbers didn’t match</h3><p>Consider these two phone numbers:</p><ul><li>+33 6 12 34 56 78</li><li>06 12 34 56 78</li></ul><p>They represent the same number, but a straightforward comparison of digits doesn’t necessarily recognize them as equivalent.</p><p>I improved the _digits normalization logic so that the country-code and domestic-prefix formats could be compared consistently.</p><p>This is a reminder that normalization isn’t merely cosmetic. It directly affects matching quality.</p><h3>Network retries still allowed a failure to escape</h3><p>The third bug was less obvious.</p><p>The project uses Tenacity to retry transient network failures. However, when retries were exhausted, Tenacity could raise its own RetryError rather than the original exception.</p><p>The calling code wasn’t handling that exception type as expected, so a persistent network issue could escape the intended fallback behavior.</p><p>The fix was to configure the relevant retry decorators with reraise=True.</p><p>This allowed the original exception to propagate into the existing error-handling logic.</p><p>For example, an unsuccessful DNS-over-HTTPS lookup should produce an unknown MX status, not incorrectly label a domain invalid or crash the workflow.</p><p>These three bugs share a common lesson: <strong>reliable automation depends on explicitly testing the edge cases and failure modes that happy-path tests tend to miss.</strong></p><p>That remembers something I dealt with in my <a href="https://medium.com/@alexandre.kuzo_66025/the-bugs-that-dont-crash-n8n-salesforce-b0a5903511b8">previous article</a>, with n8n and Salesforce working together. Automations can work smoothly with green lights, but some ghost bugs can never be diagnosed without sample test data.</p><h3>3. Where does the LLM fit?</h3><p>The project includes an LLM-assisted judgment path, but there is an important limitation: <strong>I have only run the workflow in heuristic mode so far.</strong></p><p>The current heuristic implementation handles high-scoring pairs directly. Less obvious pairs can be routed to an LLM, with retries and a heuristic fallback if the call fails.</p><p>I’ve tested the heuristic behavior and fallback mechanisms, but I haven’t yet evaluated real LLM decisions.</p><p>That distinction matters.</p><p>A confidence score of 0.90 doesn’t automatically mean there’s a 90% probability that two records belong to the same person. It could simply be a score produced by a heuristic or a model’s assessment of the available evidence.</p><p>Before allowing high-confidence matches to bypass human review, I’d want to validate the decision thresholds against labeled data.</p><p>I’d also want to compare deterministic matching with LLM-assisted judgment on exactly the same candidate pairs.</p><p>Does the LLM identify genuine duplicates that the heuristics miss? Does it introduce false positives? Is any improvement worth the additional latency, cost and complexity?</p><p>Until that experiment is done, the LLM remains an approach to evaluate, not a demonstrated improvement.</p><h3>4. What would it take to use this in production?</h3><p>The proof of concept includes tests for scoring, blocking, merge logic, enrichment and the complete graph, including the human-review interruption cycle.</p><p>But passing tests doesn’t establish that a matching system is accurate on real-world data.</p><p>Before considering production use, I’d prioritize:</p><ul><li><strong>Evaluation:</strong> measure precision, recall, false positives and false negatives on a labeled dataset.</li><li><strong>Better candidate grouping:</strong> handle clusters of related records rather than treating every pair as an independent decision.</li><li><strong>Persistent human review:</strong> replace the in-memory checkpoint and terminal prompt with a durable workflow and an appropriate review interface.</li><li><strong>Safe Salesforce operations:</strong> implement and validate actual merge and conversion operations, with appropriate permissions and safeguards.</li><li><strong>Operational resilience:</strong> handle network failures, retries and repeated execution without creating inconsistent outcomes.</li></ul><p>These are not unique to LangGraph. They are the engineering challenges that appear whenever automation starts making decisions about business-critical data.</p><h3>Conclusion: use AI where it adds value</h3><p>This project reinforced an idea I’ve also encountered while building n8n and Salesforce integrations: the interesting problems often appear at the boundaries.</p><p>What happens when data is incomplete? When two fields disagree? When a network call fails? When a seemingly perfect match is based on missing information?</p><p>LangGraph provides a useful structure for experimenting with these questions, particularly when a workflow needs conditional routing and human intervention.</p><p>But choosing an agent framework doesn’t solve the underlying data-quality problem. The matching logic still needs to be tested, the thresholds justified and the consequences of incorrect decisions controlled.</p><p>My next step is to compare the heuristic baseline with real LLM-assisted judgment on a labeled dataset.</p><p>The question isn’t whether we can add an LLM to a CRM workflow.</p><p><strong>It’s whether doing so makes the workflow better, and whether we can demonstrate that it does.</strong></p><p><em>This project is an experimental proof of concept. Salesforce merges are not executed, and the LLM-assisted matching path has not yet been evaluated.</em></p><p><strong>Get the repo:</strong> <a href="https://github.com/AlexandreKuzo/sf_langgraph_dedup_poc">sf_langgraph_dedup_poc on GitHub</a></p><p>Thanks for reading!</p><p><a href="https://alexandrekuzo.com/"><strong>Alexandre</strong></a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0d68ee1c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bugs That Don’t Crash (n8n + Salesforce)]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/the-bugs-that-dont-crash-n8n-salesforce-b0a5903511b8?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0a5903511b8</guid>
            <category><![CDATA[go-to-market]]></category>
            <category><![CDATA[revops]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 13:48:22 GMT</pubDate>
            <atom:updated>2026-10-23T13:48:22.313Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built a pre-send CRM check for outbound with n8n and Salesforce, and why a test set mattered more than the workflow.</em></p><h3>The most expensive cold email</h3><p>An unfortunate and common error is an email sent to a customer in the middle of a negotiation. The account executive finds out when the prospect forwards it, slightly annoyed, asking whether anyone at your company talks to each other (ouch!).</p><p>This mistake has often the same root cause: the prospecting list does not talk to the CRM. Lists are built in enrichment tools, cleaned in spreadsheets and loaded into sequencers. The CRM, where the truth about customers, open deals and account ownership lives, sits on the side.</p><p>I am a Salesforce developer and keen on exploring how it goes on the “other side”, where operations state their needs. I identify this side as the “<strong>GTM and RevOps world</strong>”.</p><p>I wanted to build the bridge: a check that runs before any sequence starts and answers one question for every prospect. <em>Is it safe to contact this company?</em></p><h3>What I built with n8n and Salesforce</h3><p>The workflow takes a raw list of prospects, compares every line with data on a Salesforce org and gives it one status. It is built in n8n, the open-source automation tool, running locally on my laptop. A great discovery on my side!</p><p>Here is the technical asset if you want to go through thee experiment:</p><p><a href="https://github.com/AlexandreKuzo/n8n_meets_salesforce">https://github.com/AlexandreKuzo/n8n_meets_salesforce</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcfciuVE_5ML0sNTSKufrQ.png" /></figure><p>The status names are in French because the project targets the French market, where the SIREN company number is the natural key.</p><p>The design rests on two workflows.</p><ul><li><strong>The main workflow</strong> reads the list, normalizes each line (SIREN, website domain, company name) and flags the duplicates inside the list itself. None of this needs the CRM.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTPkNWWwY2xYpVTzlL-glg.png" /></figure><ul><li><strong>A CRM sub-workflow</strong> receives the cleaned list, runs one SOQL query and does the matching. Everything Salesforce-specific lives here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*0auWfM2PQ9769pBX6Dn1Fw.png" /></figure><p>That split is deliberate. As far as I know, many outbound teams in smaller companies run HubSpot and not Salesforce. To switch CRM, I only replace the sub-workflow. The normalization and the list logic stay the same. Here is an overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sqe7GZf2VrPMJrm5z48bHw.png" /></figure><h3>Matching from the most reliable key to the least</h3><p>Each prospect is matched against Salesforce accounts in three tiers. The workflow stops at the first tier that finds a match.</p><ol><li><strong>SIREN, exact.</strong> The French company registration number is the strongest key. A value that is empty or not nine digits is ignored rather than trusted.</li><li><strong>Normalized domain, exact.</strong> When the SIREN is missing, the website does the job, once cleaned.</li><li><strong>Approximate name, weighted by city.</strong> When no strong key exists, the closest company name is scored from 0 to 1.</li></ol><p>Normalizing the domain sounds trivial, and it is the step that makes tier 2 work. The same company shows up as https://www.acme.fr, acme.fr/contact or www.Acme.fr/?ref=li. Compared raw, those are three companies. When normalized, they become one:</p><pre>function normDomaine(url) {<br>  if (!url) return &#39;&#39;;<br>  return String(url).trim().toLowerCase()<br>    .replace(/^https?:\/\//, &#39;&#39;)<br>    .replace(/^www\./, &#39;&#39;)<br>    .split(/[\/?#]/)[0];<br>}</pre><p>The Salesforce side stores the same value in a dedicated text field marked as External ID, so it is indexed. Both sides must apply exactly the same rule. If they drift apart, matching fails without a single error message.</p><p>For names, the workflow strips what LinkedIn and enrichment tools add: capital letters, accents, legal forms such as SAS or SARL, emojis and taglines after a pipe. “MENTORYA 🚀 | Mentorat pro” becomes “mentorya”. It then scores similarity with a Dice coefficient on character pairs. The score gains 0.1 when the city matches and loses 0.15 when it differs. The threshold sits at 0.8.</p><p>One rule matters more than any formula: <strong>the workflow never decides on a name alone.</strong> A name-only match never becomes “existing customer”. It becomes “probable duplicate” and goes to a human. That is what a RevOps lead wants to see: the tool narrows the doubt, a person resolves it.</p><h3>A test set with a known answer</h3><p>Before building anything, I generated a sample dataset. Without a known answer, you can only say a workflow “seems to work”. With one, you can say how often it is right, and how it fails.</p><p>The dataset is fully fictional, so no personal data is involved. It targets one ideal customer profile (ICP): French training companies and B2B EdTech.</p><ul><li><strong>20 Salesforce accounts and 6 opportunities.</strong> Some accounts are customers, three carry an open deal, six belong to a salesperson. One legacy account has neither SIREN nor website.</li><li><strong>30 incoming prospects</strong>, formatted like a raw export from an enrichment tool.</li><li><strong>The expected status for each of the 30 lines.</strong> This is the ground truth the output is graded against.</li></ul><p>Prospects are deliberately messy. They include company names in capital letters with “SAS”, an emoji and a tagline, URLs with www and a path, a typo, a missing accent, an invalid SIREN reading &quot;SIREN INCONNU&quot;, a line with an empty name, and duplicates inside the list.</p><p>The most useful lines are the <strong>false friends</strong>: three companies whose names are close to an existing account but which are different businesses. “Formatech Industrie” is not “Formatech Conseil”, even in the same city. These lines punish matching that is too permissive. Four probable duplicates (a typo, a truncated name, an article plus “SARL”, a legacy record with no keys) “punish” matching that is too strict.</p><p>The tension between those two groups is the whole point. Any threshold is a trade-off between them, and the test set makes that trade-off visible instead of anecdotal.</p><h3>Results: 30 out of 30, on the third run</h3><p>The final run returns the expected status for all 30 prospects. It did not get there on the first try, and the path matters more than the score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6A4BGaLp_V_5Kd93YmwsqA.png" /></figure><p>The hard cases held from the start. All three false friends came out as “OK to contact”, and all four probable duplicates went to human review.</p><p>The threshold has a real margin. The hardest true duplicate (“Institut Hexagone” against “Institut Hexagone Formation”, same city) scores 0.86. The closest false friend (“Cursus Digital Santé” against “Cursus Digital”, different city) scores 0.66. A threshold of 0.8 sits between them. Without the city weighting, those two cases would be much harder to separate, because the names alone are about as similar.</p><p>This margin is measured on 30 lines. It is a proof of method, not a benchmark. On a real CRM with thousands of accounts, the threshold has to be measured again on a labelled sample of that CRM.</p><h3>The bugs that don’t crash</h3><p>None of the problems I hit stopped the workflow. Every run went green. The workflow was simply wrong, and only the expected results showed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*h5PMz0Yokjm9iv3VaoMI6w.png" /></figure><h3>1. A SIREN stored as a number</h3><p>In the first run, the SIREN tier never matched once. Every match went through the domain instead, and the statuses were still right, by luck: each test account also had a website.</p><p>The cause: the SIREN field in Salesforce was a Number field. The API returned 991043324 as a number, and the code compared it with the string &quot;991043324&quot; from the CSV. In JavaScript, a Map lookup does not convert types, so the keys never met. The fix converts every SIREN to a nine-character string and restores leading zeros, which a Number field silently drops.</p><p>In production, without a test set, nobody would have noticed. The SIREN tier would have looked fine until the day a prospect had no website.</p><h3>2. Two IDs for the same user</h3><p>The first run flagged every account as “owned by a salesperson”, including the ones I owned. Salesforce record IDs exist in two forms: 15 characters, often shown in the interface, and 18 characters, always returned by the API. A strict comparison between the configured owner ID and the one the API returns is fragile. The fix compares the first 15 characters only, so both forms work.</p><h3>3. Accents broken at import</h3><p>Account names came back from Salesforce as “Campus Num√©rique” instead of “Campus Numérique”. The CSV had been read in the wrong encoding during the import, and the damaged names were stored as such. In a list view, nobody notices. In a similarity score, it costs points: one probable duplicate dropped from 1.1 to 0.98. On shorter names, that loss would be enough to miss a duplicate.</p><h3>4. One query per prospect</h3><p>n8n runs most nodes once per incoming item. With 30 prospects arriving, the Salesforce node ran the same SOQL query 30 times until I enabled its “Execute Once” setting. Thirty queries is harmless. 50,000 is an API limit.</p><p>The common thread: data errors don’t break a flow, they make it wrong. That is the strongest argument I know for a test set with a known answer.</p><h3>n8n through a Salesforce developer’s eyes</h3><p>I came to n8n with Apex and Flow habits. Some of them were useful. Others misled me.</p><p><strong>What was useful.</strong> Bulkification is the right instinct for n8n’s item model: you think in collections, not single records. Upsert by External ID makes a workflow safe to re-run. Splitting logic into an orchestrator and reusable sub-workflows mirrors the trigger handler pattern. And the Code node is plain JavaScript, so map, filter and reduce work as they do anywhere.</p><p><strong>What misled me.</strong> Flow and Apex loop explicitly; n8n iterates implicitly, so adding a Loop node out of habit is the classic first mistake. Apex rolls back a whole transaction on an exception; n8n has no rollback, so writes belong at the end of the chain. And weak typing lets an empty or mistyped field pass without a sound, which is exactly how the SIREN bug happened.</p><p><strong>Where n8n shines.</strong> I had a working end-to-end flow in a few hours, assistd with an LLM. A RevOps lead can open it, follow the boxes and change a field without reading code. For a client who wants to keep control of their automation, that matters.</p><p><strong>Where a code-first framework wins.</strong> My normalization function lives in two Code nodes, because n8n’s Community Edition has no shared code module. If someone edits one copy and not the other, matching degrades silently. There are no native unit tests either: my test set lives outside the tool. In a code-first framework such as LangGraph, normalization would be one imported function with its own tests, versioned in Git.</p><p>My conclusion is not “one tool is better”. n8n seems the right layer for orchestration and integrations that a client can see and touch. Logic that needs state, tests and evaluation belongs in code, called from that layer. Knowing where to draw that line is the skill.</p><h3>What I would tell an outbound team</h3><ol><li><strong>Check the CRM before you enrich, not after.</strong> Excluding customers, open deals and owned accounts first saves enrichment credits and protects the deals your sales team is already working.</li><li><strong>Match from the strongest key down.</strong> A registration number, then a normalized domain, then the name. Store the normalized keys in the CRM as indexed fields.</li><li><strong>Never let a name alone decide.</strong> Send name-only matches to a human. The tool narrows the doubt; a person resolves it.</li><li><strong>Build the test set before the workflow.</strong> Thirty labelled lines, false friends included, told me more than any number of green runs.</li></ol><p>Two limits remain before this goes near a production CRM. The query currently loads every account, which is fine for 20 and not for 50,000: it should filter by SIREN and domain first, then shortlist candidates for name matching. And the threshold must be measured again on a labelled sample of real data.</p><p>Next, I’d like to rebuild the same matching logic in LangGraph, run it on the same 30 lines, and compare the two approaches on the same ground truth. That comparison may come in my next article.</p><p>Thanks for reading!</p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0a5903511b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Lead Scoring in Salesforce + Fallback When the LLM Is Down (SSR Stack recipe 10)]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/ai-lead-scoring-in-salesforce-fallback-when-the-llm-is-down-ssr-stack-recipe-10-452ecc6e82b0?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/452ecc6e82b0</guid>
            <category><![CDATA[lead-scoring]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[apex]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 15:53:32 GMT</pubDate>
            <atom:updated>2026-09-08T15:53:32.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHhn4DI0qqOXGCgCdZqZlg.png" /></figure><p><em>Salesforce Slack Recipes — Recipe 10</em></p><p>A new Lead lands in Salesforce. Before a human handles it, it should be scored against your ICP (Ideal Customer Profile, if you work with), routed to the right place: hot leads assigned and called back within the hour, lukewarm ones dropped into nurturing, cold ones disqualified with a reason. Of course, the owner notified in Slack. Recipe 10 does exactly that: an LLM scores the lead when you have an API key, and a deterministic rule engine takes over when you don’t, so the pipeline never stalls on an OpenAI timeout or on a client’s data policy that says Lead data doesn’t leave the org.</p><p>It also shipped with a bug that mocked Apex tests couldn’t catch. More on that below.</p><p><em>I decided to work with Apex asynchronous calls first, before maybe plugging Agentforce. I’m still having issues when it comes to make the feature easily deployable in sandboxes.</em></p><h3>Architecture</h3><p>Same four-layer pattern as the rest of the SSR Stack: a thin Flow trigger, an async Apex worker, a scoring/routing service, and a notification layer that reuses what earlier recipes already built.</p><pre>Lead created (or updated while Score__c is still blank), with a Company, not converted<br>      │<br>      ▼<br>Record-Triggered Flow  &quot;SSR Recipe 10 - Lead Qualification&quot;  (after-save, async path)<br>      │  calls an Invocable Apex action<br>      ▼<br>LeadQualificationInvocable  →  System.enqueueJob(LeadQualificationQueueable)<br>      │  (returns immediately: queued = true)<br>      ▼<br>LeadQualificationQueueable.execute()<br>      ├─ scoreLead()      → OpenAI gpt-4o-mini  → JSON { score, reasoning, confidence }<br>      │                     └─ on no key / timeout / bad JSON → rule-based fallback<br>      ├─ route()          → thresholds from SSR_Lead_Scoring_Config__mdt → HOT / NURTURE / DISQUALIFIED<br>      ├─ notify()         → Slack via SlackService, else e-mail to the Lead owner<br>      └─ DML              → write Score__c / AI_Reasoning__c / Confidence__c / Scored_At__c<br>                            + owner / status / Task &quot;Rappeler sous 1h&quot; / CampaignMember</pre><p>The entry point is a <strong>record-triggered Flow</strong>, so the callout to OpenAI can’t be synchronous. The Flow itself does almost nothing; all the logic lives in testable Apex, which is where I want it.</p><h3>The Flow trigger</h3><p>SSR_Recipe10_Lead_Qualification.flow-meta.xml — RecordAfterSave, CreateAndUpdate, entry condition as a formula:</p><pre>AND( ISBLANK({!$Record.Score__c}), NOT(ISBLANK({!$Record.Company})), NOT({!$Record.IsConverted}) )</pre><p>It fires on create, and on any update <em>while the Lead is still unscored,</em> so editing Industry or Employees on an old, unscored Lead re-qualifies it. ISBLANK(Score__c) doubles as the loop guard: once the Queueable writes Score__c, the condition no longer matches.</p><p>Shipped as <strong>Draft</strong>, like every SSR Stack recipe, the admin flips it on when ready.</p><h3>Scoring: LLM, or a fallback that never leaves the org</h3><p>LeadScoringService.scoreLead() follows the same shape as Recipe 08&#39;s CaseSummaryService: try OpenAI, and silently fall back if anything about that call goes wrong.</p><pre>public static ScoreResult scoreLead(Lead lead) {<br>    if (lead == null) {<br>        return new ScoreResult(false, null, null, null, null, &#39;Lead is required.&#39;);<br>    }<br>String apiKey = resolveOpenAiApiKey();          // SSR_Slack_Settings__c.OpenAI_Api_Key__c<br>    if (String.isNotBlank(apiKey)) {<br>        try {<br>            ScoreResult ai = callOpenAi(apiKey, lead);<br>            if (ai != null &amp;&amp; ai.success) {<br>                return ai;<br>            }<br>        } catch (Exception ex) {<br>            // Fall through to rule-based scoring.<br>        }<br>    }<br>    return buildRuleBasedScore(lead);<br>}</pre><p>The LLM call uses gpt-4o-mini at temperature = 0.2 with response_format: json_object. The system prompt forces the shape:</p><pre>Tu es un SDR expert en qualification de leads B2B.<br>Tu notes un lead de 0 à 100 selon son adéquation avec l&#39;ICP fourni.<br>Réponds UNIQUEMENT avec un objet JSON valide de la forme :<br>{&quot;score&quot;: &lt;entier 0-100&gt;, &quot;reasoning&quot;: &quot;&lt;2-3 phrases en français&gt;&quot;, &quot;confidence&quot;: &lt;nombre 0-1&gt;}</pre><p>The user prompt is the ICP text (from SSR_Lead_Scoring_Config__mdt.Icp_Description__c) + the Lead&#39;s own fields:</p><ul><li>company,</li><li>industry,</li><li>employees,</li><li>title,</li><li>email,</li><li>country,</li><li>source</li></ul><p>parseAiContent() deserializes the response, clamps score to 0–100 and confidence to 0–1, and returns null — which routes to the fallback — if score or reasoning is missing. That defensive parsing is the whole point: an LLM that answers in prose instead of JSON must not be allowed to break the pipeline.</p><p>The fallback itself isn’t a toy version of the feature, it’s a real, deterministic mode:</p><pre>Decimal score = 30;                                    // base<br>// + industry points from SSR_Lead_Industry_Score__mdt (Technology +25, Finance/Banking +20, …)<br>// + size band: &gt;=1000 → +30 | &gt;=200 → +20 | &gt;=50 → +10 | else 0<br>// + has Email AND Title → +10<br>score = clampScore(score);                             // 0–100<br>// confidence is fixed at 0.4 in fallback mode</pre><p>This is the zero-dependency, zero-data-sharing mode a genuine selling point for a prospect whose DPO doesn’t want Lead data going to a third-party API. ScoreResult.mode records &quot;openai&quot; or &quot;fallback&quot;, and it&#39;s surfaced right in the Slack message, so nobody has to guess which engine made the call.</p><h3>Routing: thresholds live in Custom Metadata, not in code</h3><p>LeadScoringService.route() reads a single SSR_Lead_Scoring_Config__mdt record (default):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Oj16NuTLr7hVsk9NNuDwQ.png" /></figure><p>Every per-tier effect lives in Apex, not the Flow, which keeps it testable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXm6t2rGSixNlD9Mio2LKA.png" /></figure><p>A safeId() helper casts the config&#39;s Id-shaped strings and returns null on anything malformed, so a fat-fingered CMDT entry degrades gracefully instead of throwing the whole job.</p><h3>Notification: Slack, else e-mail</h3><pre>private void notify(Lead lead, ScoreResult scoreRes, RoutingResult routing) {<br>    String message = SlackService.appendRecordLink(<br>        LeadScoringService.buildSlackMessage(lead, scoreRes, routing), lead.Id);<br>SlackService.PostMessageResult posted;<br>    try {<br>        String channelId = SlackService.resolveChannelIdForRecipe(routing.slackRecipeKey);<br>        posted = SlackService.postMessage(channelId, message);<br>    } catch (Exception ex) {<br>        posted = null;                       // key not configured / inactive<br>    }<br>    if (posted == null || !posted.success) {<br>        LeadScoringService.sendEmailFallback(lead, message);   // native fallback<br>    }<br>}</pre><p>This reuses the base SlackService from Recipe 01 — nothing new needed on the Slack side, the existing chat:write scope is enough. A HOT lead produces something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*kHhn4DI0qqOXGCgCdZqZlg.png" /></figure><h3>What broke in the sandbox (and why the tests didn’t catch it)</h3><p>The Flow was active, three demo Leads went in, and everything <em>looked</em> fine:</p><pre>$ sf data query --query &quot;SELECT Status, NumberOfErrors FROM AsyncApexJob<br>                         WHERE ApexClass.Name=&#39;LeadQualificationQueueable&#39; ...&quot;<br>Completed | 0<br>Completed | 0<br>Completed | 0</pre><p>Leads got scored — 95, 40, 0 — Scored_At__c was set, the HOT lead got its Task. But nothing showed up in Slack. No error anywhere. Jobs Completed, NumberOfErrors = 0.</p><p>Testing the Slack layer in isolation worked fine:</p><pre>$ sf apex run   // SlackService.postMessage(&#39;C0BV2R6PKBR&#39;, &#39;...&#39;)<br>SSR10 auth.test  → {&quot;ok&quot;:true,&quot;user&quot;:&quot;salesforcebots&quot;,...}<br>SSR10 postMessage success=true</pre><p>Token fine, channel fine, code path fine — in isolation. So I enabled a trace flag, inserted one Lead, and pulled the Queueable’s debug log:</p><pre>|CALLOUT_REQUEST |[94]|System.HttpRequest[Endpoint=https://api.openai.com/v1/chat/completions, Method=POST]<br>|CALLOUT_RESPONSE|[94]|System.HttpResponse[Status=OK, StatusCode=200]          ← OpenAI call OK<br>|METHOD_ENTRY    |[94]|LeadQualificationQueueable.notify(...)<br>|METHOD_ENTRY    |[105]|SlackService.postMessage(String, String)<br>|EXCEPTION_THROWN|[46]|System.CalloutException: You have uncommitted work pending.<br>                       Please commit or rollback before calling out<br>|CONSTRUCTOR_ENTRY|[49]|SlackService.PostMessageResult   ← caught, returned success=false</pre><p>The OpenAI call at the top of execute() succeeds, it runs <strong>before</strong> any DML. By the time notify() runs, the Queueable has already done update leadUpdate and insert Task. Apex forbids a callout once there&#39;s uncommitted DML in the transaction. SlackService catches the CalloutException and folds it into PostMessageResult(success = false), which notify() treated as &quot;Slack said no&quot; — not &quot;Slack was never actually called.&quot; Silent failure, end to end.</p><p>Here’s the part that made me re-check my test coverage: the unit tests use Test.setMock(HttpCalloutMock.class, ...), and <strong>mocked callouts don&#39;t enforce the uncommitted-work rule.</strong> So queueable_scoresRoutesAndNotifiesSlack happily called the &quot;Slack&quot; mock after DML and asserted a clean run, green across the board. The bug only shows up against a real org — a mocked callout is a callout with the physics turned off.</p><p>The fix is a reorder: every callout has to precede the first DML in execute(), the same ordering Recipe 07&#39;s channel provisioner already uses (all conversations.* calls first, then update Opportunity last):</p><pre>LeadScoringService.RoutingResult routing = LeadScoringService.route(lead, scoreRes);<br>// Notify FIRST: every callout (LLM above, Slack here) must run before any DML.<br>notify(lead, scoreRes, routing);<br>// …then all the DML: update Lead, insert Task, insert CampaignMember</pre><p>Worth naming the trade-off out loud: the notification now fires <em>before</em> the score is persisted, so a later DML failure means you notified about a write that didn’t land. For a best-effort Slack ping, that’s the right call — the surrounding DmlException catch still guarantees the score itself is never silently lost. I also hardened the fallback so it e-mails on <em>any</em> Slack failure (ok:false, bot not in the channel), not only when the channel key fails to resolve.</p><p>Same trace, after the fix:</p><pre>|CALLOUT_REQUEST |[94]|...api.openai.com/v1/chat/completions      → 200<br>|CALLOUT_REQUEST |[46]|...slack.com/api/chat.postMessage          → 200<br>|VARIABLE_ASSIGNMENT|[109]|posted|{&quot;slackTs&quot;:&quot;1788811966.039809&quot;,&quot;success&quot;:true}<br>      ← then DML: update Lead, insert Task</pre><p>Message delivered. Lead scored 95, one Task, one Slack post. In async Apex, <em>callouts before DML</em> isn’t a style preference — it’s the platform’s physics, and your mocks won’t remind you of it.</p><h3>Live demo results</h3><p>Real gpt-4o-mini output against a sandbox, no cherry-picking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deoxa_FOF0Gly-FYHK58gg.png" /></figure><p>The reasoning for the disqualified lead, quoted verbatim (French ^^):</p><blockquote><em>« Le lead ne correspond pas à l’ICP car il s’agit d’une petite entreprise de retail avec moins de 10 employés, ce qui est en dehors des critères définis. De plus, le secteur n’est pas inclus dans la liste des secteurs cibles. »</em></blockquote><p>And the fallback-mode reasoning for that same hot lead, with the OpenAI key removed, for contrast:</p><blockquote><em>« Scoring par règles (LLM indisponible). secteur Finance (+20), effectif 450 (+20), contact décideur identifié (+10). Score = 80/100. »</em></blockquote><p>The LLM and the rule engine disagree — 95 versus 80 — and that’s fine. The rule engine is a floor, not a replacement: it exists to keep the pipeline moving and honest, not to match the LLM’s judgment exactly.</p><h3>Testing notes</h3><p>22 Apex tests: LeadScoringService at 89% coverage, LeadQualificationQueueable at 82%, the Invocable action at 89%. @TestVisible override hooks mirror CaseSummaryService: testOpenAiApiKeyOverride, testOpenAiResponseOverride, forceNoOpenAiKeyInTest, plus testConfigOverride for the threshold CMDT.</p><p>One gotcha worth flagging: once the Flow is active, insert lead inside a test also enqueues the real job — so a test asserting System.assertEquals(1, [SELECT COUNT() FROM Task]) gets Actual: 2 from the duplicate async run. The fix is to create test Leads with Score__c = 0, so the Flow&#39;s ISBLANK condition skips them and the test drives the Queueable explicitly instead. The callout-before-DML ordering also carries an explicit comment in the code, because no unit test can defend it — only a real org can.</p><h3>What’s in the box</h3><pre>classes/  LeadScoringService, LeadScoringServiceTest, LeadQualificationInvocable,<br>          LeadQualificationQueueable, LeadQualificationApiMock<br>objects/  Lead.Score__c, Lead.AI_Reasoning__c, Lead.Confidence__c, Lead.Scored_At__c,<br>          Lead.Disqualification_Reason__c<br>          SSR_Lead_Scoring_Config__mdt (+ 7 fields), SSR_Lead_Industry_Score__mdt (+ 2 fields)<br>customMetadata/  SSR_Lead_Scoring_Config.default, SSR_Lead_Industry_Score.{Technology,Finance,Banking},<br>                 SSR_Slack_Recipe.recipe_10<br>flows/    SSR_Recipe10_Lead_Qualification  (Draft)<br>manifest/ ssr-recipe10-package.xml<br>scripts/apex/  demo-recipe10-lead.apex</pre><h3>Closing thoughts</h3><p>The fallback path is what makes this recipe deployable rather than just demoable: it runs with or without an AI budget, and with or without sending Lead data to a third party, decided per client, per DPO, in one CMDT record.</p><p>And if you’re writing async Apex with any external callout in it: put every callout before your first DML statement. Write it as a comment if you have to, because your mocked tests will pass either way.</p><h3>Deploy it</h3><pre>sf project deploy start --manifest manifest/ssr-recipe10-package.xml --target-org my-org<br># then: set OpenAI key (optional), point SSR_Slack_Recipe.recipe_10 at a real channel,<br>#       assign SSR_Slack_User, activate the Flow</pre><p>Thanks for reading! Repository is here: <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">https://github.com/AlexandreKuzo/salesforce-slack-recipes</a></p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=452ecc6e82b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Receipt to Approval: building an AI Expense Manager on Salesforce]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/from-receipt-to-approval-building-an-ai-expense-manager-on-salesforce-bd6ba9fb0f53?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd6ba9fb0f53</guid>
            <category><![CDATA[salesforce-einstein]]></category>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[lwc]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 13:51:20 GMT</pubDate>
            <atom:updated>2026-08-13T13:51:20.026Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Exploring Agentforce, AgentScript, LWC, OCR and Salesforce automation through a complete end-to-end POC</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UmbXfhxhugg1sY7ag3_rg.png" /><figcaption>Oh! A Lightning App :-)</figcaption></figure><p>Your colleagues just got back from a business trip. They have a stack of receipts: a train ticket, a hotel invoice, a restaurant bill. Now they need to file an expense report.</p><p>In most organisations, that means: open a spreadsheet or an external SaaS type the merchant name, the date, the amount, attach the PDF, hit “submit”, and wait. Every. Single. Time.</p><p>What if they could just upload the receipt and let AI do the magic?</p><p>That’s the idea behind this POC.</p><h3>Why build this on Salesforce?</h3><p>Plenty of well-established SaaS tools handle pretty well expense management. So why build your own on Salesforce? From my point of view, I see at least three reasons:</p><ul><li><strong>Every organisation has its own rules… and edge cases.</strong> Approval thresholds, category policies, quota per employee type, multi-level validation. A SaaS rarely fits perfectly. Salesforce gives you the flexibility to model exactly your process.</li><li><strong>No separate account management.</strong> In any organisation already running Salesforce, every employee already has a user account. No SSO headache, no duplicate identity management, no licence to buy on another platform.</li><li><strong>Permissions, hierarchy and sharing built in.</strong> Role hierarchy, profiles, permission sets, sharing rules… Salesforce handles all of this natively. Your expense approver sees what they should see, nothing more.</li></ul><p>And with Agentforce shaking the ecosystem for a while now, there’s a real opportunity to take this further: let AI extract receipt data, guide the user through the submission, and flag automatically missing information if needed.</p><h3>What’s in this POC?</h3><p>The <a href="https://github.com/AlexandreKuzo/SF_ExpenseAssistant">GitHub repository</a> contains a deployable Salesforce project with:</p><ul><li><strong>A Lightning Web Component:</strong> (expenseClaimUploader), which handles document upload (PDF, PNG, JPG) and runs OCR directly in the browser using <a href="https://tesseract.projectnaptha.com/"><strong>Tesseract.js</strong></a> and <a href="https://mozilla.github.io/pdf.js/"><strong>pdf.js</strong></a></li><li><strong>Einstein AI extraction:</strong> a Prompt Template (Expense_Receipt_Extraction) that parses the OCR text and returns structured data: merchant, date, amount, category</li><li><strong>AgentScript:</strong> an Agentforce agent (ASC_Expense_Agent) that orchestrates the flow, prompts the user for missing information, and submits the claim</li><li><strong>Approval workflow: </strong>quota control, manager notification via Slack, and a validation/rejection cycle for administrators</li></ul><p>In this article, we’ll focus on the three most technically interesting parts: the LWC with OCR, the Einstein extraction, and AgentScript. The rest is to come.</p><h3>What it looks like in a sandbox</h3><p><a href="https://youtu.be/a6X7fW1iTw8">https://youtu.be/a6X7fW1iTw8</a></p><p>The flow is simple from the employee’s perspective:</p><ol><li>Upload a PDF or JPG receipt</li><li>OCR runs in the browser — merchant name and amount are detected automatically</li><li>If anything is missing, the agent prompts the user to fill it in</li><li>Submit — the expense claim is created in Salesforce with Pending_Approval status</li></ol><p>Pretty smooth, right?</p><h3>Architecture</h3><pre>┌─────────────────────────────┐<br>│   LWC expenseClaimUploader  │<br>│  Tesseract.js + pdf.js OCR  │  ← Browser-side, no server callout<br>└──────────────┬──────────────┘<br>               │ OCR text<br>               ▼<br>┌─────────────────────────────┐<br>│  Einstein Prompt Template   │<br>│  Expense_Receipt_Extraction │  ← Structured extraction via LLM<br>└──────────────┬──────────────┘<br>               │ JSON: merchant / date / amount / category<br>               ▼<br>┌─────────────────────────────┐<br>│  Agentforce Agent Script    │<br>│     ASC_Expense_Agent       │  ← Orchestration + user guidance<br>└──────────────┬──────────────┘<br>               │<br>       ┌───────┴────────┐<br>       ▼                ▼<br>┌────────────┐   ┌──────────────────┐<br>│ Expense    │   │ Slack notification│<br>│ Claim__c   │   │ (webhook / SSR)  │<br>│ (created)  │   └──────────────────┘<br>└────────────┘</pre><h3>The LWC — OCR directly in the browser</h3><p>The first design decision: <strong>where does OCR run?</strong></p><p>The alternative would have been to send the document to an Apex endpoint, call an external OCR API (Google Vision, AWS Textract…), and return the result. Simpler in theory, but it means an external API key to manage, a callout quota to watch, and data leaving Salesforce before we even process it.</p><p>Instead, we run OCR <strong>entirely client-side</strong>, inside the LWC, using two libraries:</p><ul><li><strong>Tesseract.js</strong> — a WebAssembly port of the Tesseract OCR engine. Handles image files (PNG, JPG) and PDFs.</li><li><strong>pdf.js</strong> — Mozilla’s PDF rendering library. Renders the first page of a PDF as a canvas element, which Tesseract can then process.</li></ul><p>Both libraries are loaded from cdn.jsdelivr.net (declared as a CSP Trusted Site in the org). For a POC this is fine — a production deployment would bundle them as Static Resources instead.</p><pre>// Simplified — LWC expenseClaimUploader<br>import { LightningElement } from &#39;lwc&#39;;<br>import { loadScript } from &#39;lightning/platformResourceLoader&#39;;<br>// 1. Load pdf.js → render PDF page to canvas<br>// 2. Pass canvas to Tesseract.recognize()<br>// 3. Send OCR text to Apex → Einstein Prompt Template</pre><p>The result: raw OCR text, extracted in the browser, ready to be sent to Einstein for structured parsing.</p><blockquote><strong><em>Trade-off to know:</em></strong><em> Tesseract works well on clean, printed receipts. Handwritten notes or low-resolution photos will produce noisy output — which is exactly why we pass the text through an LLM extraction step rather than trying to parse it with regex.</em></blockquote><h3>Einstein extraction — the Prompt Template</h3><p>Once we have OCR text, we need to turn it into structured data. That’s the job of the Expense_Receipt_Extraction Prompt Template, configured in Prompt Builder.</p><p>The prompt is straightforward:</p><pre>You are an expense receipt parser. Extract the following fields from the OCR text below.<br>Return a valid JSON object only — no explanation, no markdown.</pre><pre>Fields to extract:<br>- merchant_name (string)<br>- transaction_date (YYYY-MM-DD)<br>- amount (number, no currency symbol)<br>- category (one of: Travel, Meals, Accommodation, Office Supplies, Other)</pre><pre>OCR text:<br>{ocr_text}</pre><p>Einstein returns a JSON string. Apex parses it and maps each field to the Expense_Claim__c record.</p><p>Two important details:</p><ul><li><strong>Demo fallback.</strong> The CMDT field Use_Demo_Extraction__c lets you switch to a rule-based extraction (regex on the OCR text) if no Einstein licence is available. This keeps the POC usable on any sandbox — the same philosophy as the OpenAI fallback in <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">Recipe 08 of the SSR Stack</a>.</li><li><strong>Structured output discipline.</strong> Prompting the LLM to return <em>only</em> JSON (no explanation, no markdown fences) is critical here. The Apex JSON parser will throw on any extra content. In production, add a String.trim() and strip any ```json fences before parsing.</li></ul><h3>AgentScript — the orchestration layer</h3><p>The most interesting part. Instead of a traditional Flow with decision elements and screen steps, we use an <strong>AgentScript</strong> file to guide the user through the submission.</p><p>The agent:</p><ol><li>Receives the extracted data (merchant, date, amount, category) as context</li><li>Identifies missing or low-confidence fields</li><li>Asks the user to confirm or complete them via natural language</li><li>Calls an @InvocableMethod to create the Expense_Claim__c record</li><li>Confirms submission and provides the record link</li></ol><p>yaml</p><pre># ExpenseManager_Expense_Agent — simplified topic instructions<br>Role: You are an expense claim assistant for employees.<br>Your job is to help the user submit an expense claim based on a receipt they have uploaded.<br>You have access to:<br>- Extracted receipt data (merchant, date, amount, category)<br>- The CreateExpenseClaim action<br>Steps:<br>1. Present the extracted data to the user for confirmation.<br>2. If any required field is missing or unclear, ask the user to provide it.<br>3. Once all fields are confirmed, call CreateExpenseClaim.<br>4. Confirm the submission with the claim number.</pre><p>Why AgentScript over a Flow? Because the interaction is <strong>conversational, not deterministic</strong>. A Flow needs every branch defined upfront. The agent adapts: if the receipt is clear, it submits in one step; if three fields are missing, it asks for them one by one in natural language.</p><p>The same agent handles both cases without a single extra decision node.</p><h3>Approval and quota control</h3><p>Once the claim is submitted (Pending_Approval status), the approval side kicks in:</p><ul><li>A Flow notifies the administrator via Slack (Incoming Webhook on Expense_AI_Settings)</li><li>The administrator validates or rejects via a Quick Action on the record</li><li>On approval, Expense_Quota__c.Used_Amount__c is recalculated the system enforces the employee&#39;s remaining budget</li><li>If the claim exceeds the remaining quota, approval is blocked</li></ul><p>The quota logic runs in Apex — a deliberate choice over a validation rule, because the calculation involves aggregating multiple approved claims per period, which a formula field can’t do cleanly.</p><h3>Deploy it yourself</h3><pre>git clone https://github.com/AlexandreKuzo/SF_ExpenseAssistant<br>cd SF_ExpenseAssistant<br>sf org login web --alias expense-poc<br>sf project deploy start --target-org expense-poc<br>sf apex run --file scripts/apex/demoData.apex --target-org expense-poc<br>sf org assign permset --name ASC_Employee --target-org expense-poc<br>sf org assign permset --name ASC_CSE_Admin --target-org expense-poc</pre><p>Then follow <a href="https://github.com/AlexandreKuzo/SF_ExpenseAssistant/blob/main/docs/agentforce-setup.md">docs/agentforce-setup.md</a> to configure the Prompt Template and publish the Agent Script.</p><blockquote><strong><em>Trailhead Playground note:</em></strong><em> Agentforce and Einstein Generative AI require a licensed org. On a Trailhead Playground, deploy with </em><em>Use_Demo_Extraction__c = true to use the rule-based fallback and test the LWC + submission flow without an AI licence. Otherwise, you may be blocked.</em></blockquote><h3>What’s next?</h3><p>This POC demonstrates something I struggled to find documented on the web: <strong>combining browser-side OCR, Einstein LLM extraction, and Agentforce orchestration in a single Salesforce deployment.</strong></p><p><strong>=&gt; I’m still looking for relevant use cases to build other solutions like this one (ideas welcome! ^^)</strong></p><p>A few directions for a production-ready version:</p><ul><li>Move Tesseract.js and pdf.js to Static Resources (remove the CDN dependency)</li><li>Replace the Slack Incoming Webhook with the SSR Stack for richer, multi-recipe notifications</li><li>Add multi-currency support on Expense_Claim__c</li><li>Give a try to <a href="https://developer.salesforce.com/docs/platform/multiframework/guide/reactdev-overview.html">Salesforce Multi-Framework</a> ; this can be a nice bet to build beautiful frontend instead of a LWC</li><li>Remove the Toasts that are unfriendly at that time</li></ul><p>The full repository is on GitHub: 👉 <a href="https://github.com/AlexandreKuzo/SF_ExpenseAssistant">github.com/AlexandreKuzo/SF_ExpenseAssistant</a></p><p>Thanks for reading, feedbacks and PRs welcome :-)</p><p><a href="https://alexandrekuzo.com/"><strong>Alexandre</strong></a><strong> 😉</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd6ba9fb0f53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Event-Driven Integration with Salesforce Platform Events and Python]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/building-an-event-driven-integration-with-salesforce-platform-events-and-python-96931bfbd549?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/96931bfbd549</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[event-platform]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 16:51:02 GMT</pubDate>
            <atom:updated>2026-07-29T16:51:02.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AadIxsFFwFW-Ab8-94klNg.png" /><figcaption>What are these? :-)</figcaption></figure><p>Your payment provider just detected a failed transaction. Your e-commerce platform knows about it. But does Salesforce?</p><p>If your CRM and your external systems aren’t talking in real time, the answer is probably: <em>not until someone manually creates a Case</em>. Platform Events exist precisely to fix that, but I found it hard to get a full end-to-end demo running, especially from an external system. It is surprisingly “underdocumented”.</p><p>This article walks through a complete POC: a Python script simulates an external payment platform publishing a Payment_Failed__e event to Salesforce, which automatically creates a support Case and, bonus (!) sends a Slack alert all without a single manual click. If you found some of my articles before, you know that I am keen on integrating Slack in meaningful workflows with the <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">SSR Stack</a>.</p><h3>Why Platform Events?</h3><p>Salesforce Platform Events are presented as the backbone of event-driven architecture on the Salesforce platform. They let external systems publish business events directly onto the Salesforce Event Bus, which any Flow or Apex trigger can then consume asynchronously.</p><p>A classic use case: a payment gateway, an ERP, a logistics platform or any external system publishes an event the moment something significant happens. Salesforce reacts in near real time.</p><p>The problem: most tutorials I found stop at <em>“configure your Platform Event object”</em> and assume you have a ready-made external publisher. This POC ships one.</p><h3>Architecture</h3><pre>┌──────────────────────┐<br>│    Python Script     │<br>│  External Simulator  │   external-event-simulator/simulator.py<br>└──────────┬───────────┘<br>           │ OAuth 2.0 Client Credentials<br>           │ POST /services/data/vXX/sobjects/Payment_Failed__e/<br>           ▼<br>┌──────────────────────┐<br>│   Salesforce API     │<br>└──────────┬───────────┘<br>           ▼<br>┌──────────────────────┐<br>│     Event Bus        │<br>│  Payment_Failed__e   │<br>└──────────┬───────────┘<br>           ▼<br>┌──────────────────────┐<br>│  Platform Event      │<br>│  Triggered Flow      │   Payment_Failed_Handle_Event<br>└──────────┬───────────┘<br>           ├──────────────► Create Case (support)<br>           └──────────────► Slack notification (SSR Stack)</pre><p>One external event → one support Case → one Slack alert. Fully automated, end to end.</p><h3>The Platform Event: Payment_Failed__e</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdAM36QxcuP2MeMUfkM3hg.png" /></figure><p>Four custom fields, one clear business purpose:</p><p>API Field Type Description External_Order_Id__c Text Order ID from the external platform Status__c Text Business status (e.g. PAYMENT_FAILED) Customer_Email__c Text Customer email Amount__c Number Transaction amount</p><p>The event is <strong>High Volume</strong> with publishBehavior: PublishAfterCommit — the standard pattern for integration events where you want guaranteed delivery after the transaction commits.</p><h3>The Triggering Flow</h3><p>In the Platform Event setup, you’ll see a “Subscriptions” item at the bottom of the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmQnIt6LgksLmClg9800Kg.png" /></figure><p>If you open it, you get a record-triggered flow with the “Payment Failed” Platform Event as a starter. Next, logic is added as in a classic flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWvFnaRn2vvt-Y0IQG5eLg.png" /></figure><h3>Recap: what’s in the repo</h3><pre>force-app/main/default/<br>├── objects/Payment_Failed__e/           # Platform Event + 4 custom fields<br>├── flows/Payment_Failed_Handle_Event    # Flow triggered by the event<br>├── permissionsets/<br>│   └── Payment_Failed_Event_Integration # Access to the Platform Event + Slack classes<br>├── customMetadata/<br>│   └── SSR_Slack_Recipe.recipe_payment_failed  # Slack channel for the alert<br>└── connectedApps/<br>    └── Payment_Event_Integration        # OAuth Client Credentials Connected App</pre><pre>external-event-simulator/<br>├── simulator.py        # The external platform Python script<br>├── requirements.txt<br>└── .env.example</pre><p>The Slack stack (SlackInvocable, SlackService, SSR_Slack_Settings__c…) is reused from the <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">SSR Stack</a> — the same framework behind the Salesforce Slack Recipes series. If you&#39;ve deployed earlier recipes, it&#39;s already on your org.</p><h3>A note on Trailhead Playgrounds — read this first</h3><p>Before diving in: <strong>Connected App creation via Metadata API is blocked on Developer Edition / Trailhead Playground orgs.</strong></p><p>If you try to deploy the Connected App component on a Trailhead org, you’ll get:</p><pre>You can&#39;t create a connected app. To enable connected app creation,<br>contact Salesforce Customer Support.</pre><p>This is a known Salesforce restriction on free dev orgs. You have two options:</p><ul><li><strong>Session mode</strong> (recommended for Trailhead): skip the Connected App entirely and reuse the Salesforce CLI access token. Fast, zero config, tests the full event chain.</li></ul><p>On a <strong>company sandbox</strong>, the Connected App deploys automatically with no manual steps.</p><h3>Before diving in, technical notes :-)</h3><p>Some elements mentioned may block your deployment and actions, please read carefully this:</p><ul><li><em>The Flow </em><em>Payment_Failed_Handle_Event is an Autolaunched Flow with </em><em>triggerType: PlatformEvent. It runs in the context of the user who published the event — which is why the Permission Set must be assigned to the integration user.</em></li><li><em>The </em><em>publishBehavior: PublishAfterCommit setting means the event is only published if the publishing transaction commits successfully. For a payment failure simulator this is the right default.</em></li><li><em>The end-to-end chain was first validated with a raw </em><em>sf api request rest call (CLI session, admin user) — before any Connected App was configured. A useful debugging technique: decouple the event publishing from the OAuth setup to isolate where issues occur.</em></li><li><strong><em>No SSR (Slack) Stack on your org?</em></strong><em> The Case creation is functionally decoupled from Slack: it happens first in the Flow, and SlackInvocable never throws — any Slack failure (bad token, missing bot) is caught internally and returned as a soft error, never rolling back the Case. That said, this repo’s Flow still references the SlackInvocable Apex action by name, so deploying it as-is on an org with zero SSR classes will fail at deploy time, not silently at runtime. To run this without any Slack integration at all, </em><strong><em>just remove the Send_Slack_Alert</em></strong><em> action from the Flow — the Event → Flow → Case chain works standalone.</em></li></ul><h3>Salesforce configuration</h3><p>Clone the Github Repo and Authenticate your org:</p><pre>git clone https://github.com/AlexandreKuzo/SF_PlatformEvent.git<br>cd SF_PlatformEvent<br>sf org login web --alias my-org</pre><h3>Deploy the Platform Event and Flow</h3><p><strong>On a company sandbox</strong> (full automated deploy):</p><pre>SANDBOX_ALIAS=&#39;my-org&#39;</pre><pre>sf project deploy start --target-org &quot;$SANDBOX_ALIAS&quot; \<br>  --source-dir force-app/main/default/objects/Payment_Failed__e \<br>  --source-dir force-app/main/default/flows/Payment_Failed_Handle_Event.flow-meta.xml \<br>  --source-dir force-app/main/default/permissionsets/Payment_Failed_Event_Integration.permissionset-meta.xml \<br>  --source-dir force-app/main/default/customMetadata/SSR_Slack_Recipe.recipe_payment_failed.md-meta.xml \<br>  --source-dir force-app/main/default/connectedApps/Payment_Event_Integration.connectedApp-meta.xml</pre><pre>sf org assign permset --target-org &quot;$SANDBOX_ALIAS&quot; \<br>  --name Payment_Failed_Event_Integration</pre><p><strong>On a Trailhead Playground</strong> (deploy everything except the Connected App):</p><pre>sf project deploy start --target-org my-org --source-dir force-app<br>sf org assign permset --target-org my-org --name Payment_Failed_Event_Integration</pre><h3>Configure the Slack channel</h3><p><strong>Setup → Custom Metadata Types → SSR Slack Recipe → </strong><strong>recipe_payment_failed</strong></p><p>Set the Channel_Id__c to your target Slack channel ID (the C... value visible in the channel URL). Make sure the SSR bot is invited: /invite @YourBotName.</p><p>If needed, don’t hesitate to check this story to fully configure the SSR Stack: <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8">https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8</a></p><h3>Option A — Test without a Connected App (session mode)</h3><p>The fastest path to a working demo — no OAuth setup required.</p><pre>export SF_INSTANCE_URL=&quot;https://your-org.my.salesforce.com&quot;<br>export SF_ACCESS_TOKEN=&quot;$(SF_TEMP_SHOW_SECRETS=true sf org display \<br>  --target-org my-org --json | \<br>  python3 -c &#39;import json,sys; print(json.load(sys.stdin)[&quot;result&quot;][&quot;accessToken&quot;])&#39;)&quot;</pre><pre>cd external-event-simulator<br>python simulator.py \<br>  --order-id ORD-2026-042 \<br>  --status PAYMENT_FAILED \<br>  --email jane@example.com \<br>  --amount 500</pre><pre>unset SF_ACCESS_TOKEN SF_INSTANCE_URL</pre><p>The simulator detects SF_ACCESS_TOKEN and switches to session mode automatically (Mode session (bypass OAuth)...). The CLI token expires after a few hours — rerun the export line to refresh it.</p><p>Or skip Python entirely and go raw CLI:</p><pre>sf api request rest &#39;services/data/v67.0/sobjects/Payment_Failed__e/&#39; \<br>  --target-org my-org -X POST \<br>  -b &#39;{&quot;External_Order_Id__c&quot;:&quot;ORD-2026-042&quot;,&quot;Status__c&quot;:&quot;PAYMENT_FAILED&quot;,&quot;Customer_Email__c&quot;:&quot;jane@example.com&quot;,&quot;Amount__c&quot;:500}&#39;</pre><h3>Option B — Full OAuth setup (Connected App)</h3><p>This simulates the real authentication flow an external platform would use.</p><p><strong>On a company sandbox</strong>, the Connected App is already deployed in Step 1.</p><p><strong>On a Trailhead Playground</strong>, create it manually (~5 minutes):</p><ol><li><strong>Setup → App Manager → New Connected App</strong></li><li>Basic Information: name it Payment Event Integration, add your contact email</li><li>Enable OAuth Settings:</li></ol><ul><li>Callback URL: <a href="https://login.salesforce.com/services/oauth2/callback">https://login.salesforce.com/services/oauth2/callback</a></li><li>Scopes: <strong>Manage user data via APIs (api)</strong></li></ul><p>Save</p><ol><li><strong>Manage → Edit Policies</strong>: enable <strong>Client Credentials Flow</strong>, set Run As to your integration user</li><li><strong>Manage Consumer Details</strong>: copy the <strong>Consumer Key</strong> and <strong>Consumer Secret</strong></li></ol><p>Then configure and run the simulator:</p><pre>cd external-event-simulator<br>python3 -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt<br>cp .env.example .env<br># Fill in SF_DOMAIN, SF_CONSUMER_KEY, SF_CONSUMER_SECRET</pre><pre># Publish one event<br>python simulator.py \<br>  --order-id ORD-2026-001 \<br>  --status PAYMENT_FAILED \<br>  --email customer@example.com \<br>  --amount 750</pre><pre># Or generate multiple events</pre><pre>python simulator.py --random --count 5 --delay 2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lvpw0pGd6kOqqyaEAGqtlQ.png" /><figcaption>Wow!</figcaption></figure><h3>Verify the result</h3><p><strong>Check the Case was created:</strong></p><pre>sf data query --target-org my-org \<br>  --query &quot;SELECT Id, Subject, Status, Priority, SuppliedEmail, CreatedDate \<br>           FROM Case ORDER BY CreatedDate DESC LIMIT 5&quot;</pre><p>A new Case — <em>“Echec de paiement — Commande ORD-2026–XXX”</em> — should appear within a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoI5OJVkOt9BCMFZ5mI-yA.png" /><figcaption>Case created!</figcaption></figure><p><strong>If Slack is configured, check the Slack notification</strong> in the channel configured on recipe_payment_failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*WFMmhB6KjD2m8-iQvlStuw.png" /><figcaption>Beautiful!</figcaption></figure><p><strong>Check the async Apex job, if needed:</strong></p><pre>sf data query --target-org my-org \<br>  --query &quot;SELECT ApexClass.Name, Status, NumberOfErrors \<br>           FROM AsyncApexJob \<br>           WHERE ApexClass.Name = &#39;SlackCalloutQueueable&#39; \<br>           ORDER BY CreatedDate DESC LIMIT 3</pre><blockquote><strong><em>Important:</em></strong><em> a Completed job with 0 errors means the Apex ran without crashing — not necessarily that the Slack message was delivered. If the bot token is invalid or the bot isn’t in the channel, the callout fails silently (by design). Check Debug Logs if the Slack message doesn’t appear.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maauBxz6luYBQWvBint0GQ.png" /></figure><h3>What’s next?</h3><p>This POC demonstrates something often skipped in Salesforce tutorials: <strong>testing Platform Events from outside Salesforce</strong>, with a real external publisher, real OAuth authentication, and a real end-to-end flow.</p><p>The same pattern adapts to any integration scenario: logistics updates, ERP stock events, SaaS webhooks. Change the event fields and the Flow logic, keep the infrastructure.</p><p>The full repository is on GitHub: 👉 <a href="https://github.com/AlexandreKuzo/SF_PlatformEvent">github.com/AlexandreKuzo/SF_PlatformEvent</a></p><p>The SSR Stack powering the Slack notifications: 👉 <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">github.com/AlexandreKuzo/salesforce-slack-recipes</a></p><p><em>Feedback and PRs welcome.</em></p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96931bfbd549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce × Slack — AI Case Summary DM’d to the Owner with the SSR Stack (Recipe 08)]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/salesforce-slack-ai-case-summary-dmd-to-the-owner-with-the-ssr-stack-recipe-08-3adec85d1e05?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/3adec85d1e05</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 14:08:27 GMT</pubDate>
            <atom:updated>2026-07-17T14:08:27.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*cCclpzuD_F5luAdV5Y_tIg.png" /><figcaption>New notiification!</figcaption></figure><p>A Support Case just got escalated — or reassigned to a new agent.</p><p>Instead of asking them to dig through email threads, status history and internal notes before their first reply, what if Salesforce handed them a ready-to-read AI briefing… directly in their Slack DMs?</p><p>That’s <strong>Recipe 08 of the SSR Stack</strong>. When a Case is escalated (IsEscalated flips to true) or its Owner changes, Salesforce automatically:</p><ol><li><strong>Loads</strong> the Case plus the last few EmailMessage records</li><li><strong>Summarizes</strong> the context with OpenAI (gpt-4o-mini) — or a structured rule-based fallback if no API key is configured</li><li><strong>Resolves</strong> the Case owner’s Slack identity via email (users.lookupByEmail)</li><li><strong>Sends a DM</strong> with the summary and a deep link back to Salesforce</li></ol><p>No shared channel noise. No <em>“who owns this?”</em>. The right person gets the briefing in their Slack DMs — before they even open the Case.</p><p>If you’re new here, start with the earlier articles in the series:</p><ul><li><strong>Introduction &amp; Recipe 01</strong> — <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8">Introducing the SSR Stack</a></li><li><strong>Recipe 02</strong> — <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-build-an-opportunity-closed-won-slack-alert-with-the-ssr-stack-recipe-02-fa300a4090a4">Closed Won Slack Alert</a></li><li><strong>Recipe 07</strong> — <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-spin-up-a-dedicated-deal-room-automatically-with-the-ssr-stack-recipe-07-241b20b15706">Deal Room Provisioning</a> <em>(email matching — same pattern reused here)</em></li></ul><h3>Why a DM — and why email?</h3><p>Earlier recipes post to a fixed Slack channel configured via Custom Metadata. Recipe 07 introduced <strong>email-based user matching</strong> to invite Opportunity owners into a newly created channel.</p><p>Recipe 08 reuses that same bridge — but for a personal, private notification.</p><p>There’s still no magic Salesforce User → Slack User link in this stack. The reliable key is the <strong>email address</strong>: Owner.Email goes to Slack&#39;s users.lookupByEmail, which returns a Slack user ID (starting with U), and that ID is used as the destination in chat.postMessage. Sending to a user ID is what creates a DM with the bot.</p><p>For this to work: <strong>the Case owner’s Salesforce email must exist in your Slack workspace.</strong></p><h3>Einstein or Prompt Builder?</h3><p>The default path in this recipe is <strong>OpenAI</strong>, because it demos cleanly against a Slack Developer sandbox with only a Custom Setting key. In a licensed Salesforce org, you can swap the LLM step for Prompt Builder or Einstein later — same Flow, same Slack DM, different summarizer.</p><p>The SSR Stack ships the OpenAI path first, with a <strong>no-key fallback</strong> so the recipe stays fully usable in demos and sandboxes without an AI bill.</p><h3>Slack configuration</h3><p>Add or confirm these Bot Token Scopes in your Slack app under <strong>OAuth &amp; Permissions → Bot Token Scopes</strong>:</p><p>Scope Why chat:write Post the DM (already set in earlier recipes) users:read.email Look up the Case owner by email (same as Recipe 07)</p><p>Reinstall the app if Slack prompts you to approve the updated scopes.</p><h3>Salesforce configuration</h3><p>Authenticate your org if needed:</p><pre>sf org login web --alias my-org</pre><h3>Step 1 — Deploy Recipe 08</h3><pre>sf project deploy start \<br>  --manifest manifest/ssr-recipe08-package.xml \<br>  --target-org my-org</pre><h3>What gets deployed?</h3><p>CaseSummaryService Prompt building, OpenAI callout, rule-based fallback</p><p>CaseSummaryQueueable Async: summarize → lookupByEmail → DM</p><p>CaseSummaryInvocable Flow entry point (@InvocableMethod)</p><p>SSR_Recipe08_Case_AI_Summary (Flow) Fires on Case escalate or Owner change</p><p>SSR_Slack_Settings__c.OpenAI_Api_Key__c Optional OpenAI key field (never commit the real value)</p><p>SSR_OpenAI (Remote Site) Allows HTTPS callouts to api.openai.com</p><p>SSR_Slack_User (Permission Set) Apex access for the new classes</p><blockquote><strong>Note:</strong> there is no recipe_08 record in Custom Metadata. The destination is the owner&#39;s DM, not a shared channel — same logic as Recipe 07 not needing a pre-created channel.</blockquote><h3>Step 2 — Optional: store the OpenAI API key</h3><p><strong>Setup → Custom Settings → SSR Slack Settings → Manage</strong></p><p>Paste your sk-... key into <strong>OpenAI API Key</strong> and save. If you don’t have an OpenAI API key, please check this =&gt; <a href="https://developers.openai.com/api/docs">https://developers.openai.com/api/docs</a></p><p>Leave it blank to use the rule-based fallback — great for sandbox demos without an API bill.</p><h3>Step 3 — Confirm the Bot Token and Permission Set</h3><p>Same as previous recipes:</p><ul><li><strong>Bot Token</strong> in SSR Slack Settings</li><li><strong>Assign SSR Slack User</strong> to the users who will trigger the Flow</li></ul><h3>Step 4 — Activate the Flow</h3><p>The Flow ships in <strong>Draft</strong> status for safety.</p><p><strong>Setup → Flows → SSR Recipe 08 — Resume Case IA</strong></p><p>Entry criteria: (IsEscalated = true AND IsEscalated IsChanged) OR (OwnerId IsChanged)</p><p>Click <strong>Activate</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RX3spY_S5Fxe9RhEVOP9rA.png" /><figcaption>Customize and activate the flow</figcaption></figure><h3>Step 5 — Add the Escalate Quick Action</h3><p>IsEscalated is a standard Salesforce checkbox — but it&#39;s intentionally not editable inline in this project. Many orgs remove it from the page layout to avoid inconsistent manual escalations, and drive it instead through Case Escalation Rules (SLA-based) or a controlled business action.</p><p>The package ships exactly that: a Quick Action called Case.SSR_Escalate_Case, labeled <strong>&quot;Escalader ce Case&quot;</strong>, that flips IsEscalated to true with a single click. No other field exposed, no raw checkbox to toggle.</p><p><strong>Setup → Object Manager → Case → Page Layouts</strong> (or Lightning App Builder → Highlights Panel)</p><p>Drag <strong>Escalader ce Case</strong> into the <em>Salesforce Mobile and Lightning Experience Actions</em> section and save.</p><blockquote><strong>The Flow’s entry criteria are yours to tune.</strong> SSR_Recipe08_Case_AI_Summary currently fires when IsEscalated becomes true or when OwnerId changes — a deliberately broad default. In Flow Builder, you can narrow or replace these conditions freely: trigger only on a Priority change, on a custom flag like Need_AI_Summary__c, on a specific Record Type, or any other Case event that fits your support process. The Quick Action and the Flow are decoupled, so you can change either side independently.</blockquote><h3>Test the integration</h3><ol><li>Open a Case whose <strong>Owner email exists in Slack</strong></li><li>Click <strong>Escalader ce Case</strong> (or reassign the Case Owner)</li><li>Wait a few seconds — the Queueable and its callouts run asynchronously</li><li>In Slack, the owner receives a DM like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQRzgHPSsw12tDRekzEczQ.png" /><figcaption>Boom!</figcaption></figure><p>Context delivered where the agent already works. Great!</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NgyIf6bSGPGKYLVgDllnA.png" /></figure><p>Everything runs asynchronously — the Flow’s synchronous path is never blocked by an external callout.</p><h3>Design choices worth shipping</h3><p>These are the decisions that make this a production-ready recipe, not just a demo:</p><ul><li><strong>DM over channel</strong> — the briefing is personal and avoids support-channel noise</li><li><strong>Email matching</strong> — reuses Recipe 07’s Slack identity bridge, no new infrastructure needed</li><li><strong>OpenAI optional</strong> — a blank key triggers a structured fallback, keeping the recipe demo-friendly</li><li><strong>Async Queueable</strong> — OpenAI and Slack callouts never run in the Flow’s synchronous path</li><li><strong>Truncated email context</strong> — last 5 emails, ~500 characters each, HTML stripped via .stripHtmlTags() — for cost control and token hygiene</li><li><strong>Silent miss on lookup</strong> — if the owner’s email isn’t in Slack, no DM is sent (check Debug Logs and Apex Jobs during setup)</li><li><strong>Controlled escalation, decoupled from the Flow</strong> — the Quick Action only sets IsEscalated; the Flow&#39;s entry criteria decide what triggers the summary, so either side can evolve independently</li></ul><h3>Troubleshooting</h3><p>Nothing in Slack =&gt; Flow <strong>Active</strong>? Permission Set assigned? Bot Token set?</p><p>OpenAI mode never used =&gt; OpenAI_Api_Key__c set? Remote Site SSR_OpenAI active?</p><p>Fallback only, always =&gt; Expected without a key ; or the OpenAI call failed (check Debug Logs)</p><p>No DM and no error =&gt; Does the owner&#39;s Salesforce email match their Slack email? Scope users:read.email enabled?</p><p>Wrong person received it =&gt; Check Case.OwnerId — recheck ownership before triggering</p><h3>What’s next?</h3><p>Recipe 08 shows the SSR Stack combining three things that rarely meet cleanly: <strong>CRM events, LLM summarization, and person-level Slack delivery</strong> — all without leaving your Salesforce metadata model.</p><p>Coming up: Agentforce pipeline monitoring, and optional Einstein / Prompt Builder variants of this same Case-summary DM for orgs with the right licences.</p><p>The full repository, manifests, and all available recipes live on GitHub: 👉 <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">github.com/AlexandreKuzo/salesforce-slack-recipes</a></p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3adec85d1e05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce × Slack — Spin Up a Dedicated “Deal Room” Automatically with the SSR Stack (Recipe 07)]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/salesforce-slack-spin-up-a-dedicated-deal-room-automatically-with-the-ssr-stack-recipe-07-241b20b15706?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/241b20b15706</guid>
            <category><![CDATA[salesforce-developer]]></category>
            <category><![CDATA[crm]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[apex]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 09:32:50 GMT</pubDate>
            <atom:updated>2026-07-08T09:32:50.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*jRJnqZFVn0eaOCCjIeDBYA.png" /></figure><p>Picture this: an Opportunity just reached <strong>Closed Won</strong>.</p><p>Instead of the usual <em>“let’s create a channel, add the account manager, ping the sales rep, drop a summary…”</em> dance, what if Salesforce did all of it for you — the moment the deal closes?</p><p>That’s exactly what <strong>Recipe 07</strong> of the SSR Stack does. When an Opportunity is won, Salesforce will automatically:</p><ol><li><strong>Create</strong> a brand-new Slack channel dedicated to that deal, for example: (#deal-acme-corp-2026)</li><li><strong>Invite</strong> the right people — the Opportunity owner and their manager</li><li><strong>Post</strong> a welcome message with the deal details and a direct link back to the record</li></ol><p>No manual setup. No forgotten stakeholders. Just a ready-to-go deal room, provisioned in seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NY1fjzfy-XVqgCVPczXovg.png" /></figure><p><em>If you’re new here, the SSR Stack is a </em><strong><em>lightweight Apex + Flow framework</em></strong><em> that lets you send rich Slack notifications from any Salesforce event without relying on the native Guided Slack Setup. </em><strong><em>The goal is NOT to replace the powerful native features currently designed</em></strong><em>. It comes as another way to use great existing assets from Salesforce and Slack if your org does not have the prerequisites to install the new products.</em></p><p>Start with the two previous articles before diving in:</p><ul><li><strong>Introduction &amp; Recipe 01</strong> — <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8">Introducing the SSR Stack</a></li><li><strong>Recipe 02</strong> — <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-build-an-opportunity-closed-won-slack-alert-with-the-ssr-stack-recipe-02-fa300a4090a4">Closed Won Slack Alert</a></li></ul><h3>What’s different this time</h3><p>The first recipes route each alert to a <strong>fixed</strong> Slack channel configured via Custom Metadata. Recipe 07 flips that logic entirely: there’s no pre-configured channel, because the channel <strong>doesn’t exist yet</strong>. Salesforce creates it on demand.</p><p>That introduces two new challenges:</p><ul><li><strong>New Slack scopes</strong> — creating channels and looking up users requires more permissions than chat:write alone</li><li><strong>Matching a Salesforce user to a Slack user</strong> — the answer is simpler than you’d think: <strong>email</strong></li></ul><p>Let’s build it.</p><h3>Slack configuration</h3><p>Recipe 07 needs a few extra bot scopes. In your Slack app, go to <strong>OAuth &amp; Permissions → Bot Token Scopes</strong> and add:</p><p>Scope Why chat:write Post the welcome message (already set in earlier recipes) channels:manage Create public channels channels:read Read channel information users:read.email Look up a Slack user by their email address</p><p>Reinstall the app if Slack prompts you to approve the new scopes, and copy your refreshed <strong>Bot User OAuth Token</strong> (xoxb-...) if it changed.</p><blockquote><strong><em>Why email?</em></strong><em> There’s no native link between a Salesforce user and a Slack account. The most reliable bridge is the </em><strong><em>email address</em></strong><em>: the SSR Stack calls Slack’s </em><em>users.lookupByEmail with the Salesforce user&#39;s email to resolve their Slack ID. For this to work, the email on the Salesforce user record must match the email registered in your Slack workspace.</em></blockquote><h3>Salesforce configuration</h3><p>As with the other recipes, everything deploys via the Salesforce CLI. Authenticate your org if needed:</p><pre>sf org login web --alias my-org</pre><h3>Step 1 — Clone the repo and deploy Recipe 07</h3><pre>sf project deploy start \<br>  --manifest manifest/ssr-recipe07-package.xml \<br>  --target-org my-org</pre><h3>What gets deployed?</h3><p>SlackChannelService =&gt; Core callouts: create channel, look up users by email, invite members, post welcome message</p><p>SlackChannelProvisionerQueueable =&gt; Async orchestration — creates the channel, resolves users, invites them, posts the message, stores the channel ID</p><p>SlackChannelInvocable =&gt; Flow entry point (@InvocableMethod)</p><p>SSR_Recipe07_Slack_Channel_Create =&gt; (Flow) Fires on Closed Won and calls the invocable</p><p>Opportunity.SlackChannelId__c =&gt; Text field storing the created channel&#39;s ID (read-only for users)</p><p>SSR_Slack_User =&gt; (Permission Set) Apex access + field-level security for the new field</p><h3>Step 2 — Confirm the Bot Token</h3><p>If you’ve already deployed an earlier recipe, your token is already stored. Otherwise:</p><p><strong>Setup → Custom Settings → SSR Slack Settings → Manage → New (Organization)</strong></p><p>Paste your xoxb-... token into <strong>Bot Token</strong> and save.</p><h3>Step 3 — Assign the Permission Set</h3><p><strong>Setup → Permission Sets → SSR Slack User → Manage Assignments</strong></p><p>Assign it to the users who will trigger the flow (typically admins and integration users). This grants both Apex access and field-level security on SlackChannelId__c.</p><blockquote><strong>A note on the read-only field.</strong> SlackChannelId__c ships as <strong>read-only</strong> in the Permission Set — intentionally. This field is a system value, written only by the integration, never by a human. Worth knowing: Apex doesn&#39;t enforce FLS by default, so the queueable can still write to it even though it&#39;s read-only for users. The FLS controls visibility and manual editing, not automated writes. A clean example of &quot;the code owns this field, the user just reads it.&quot;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOvDmKwIeDmv5v0wPQQxgQ.png" /><figcaption>If the SlackChannelId__c field is not visible in the flow, get an eye on FLS in Setup</figcaption></figure><h3>Step 4 — Set the owner’s manager (optional but recommended)</h3><p>To invite both the sales rep and their manager, the Opportunity owner needs a <strong>Manager</strong> set on their User record:</p><p><strong>Setup → Users → open the owner’s record → set the Manager field</strong></p><p>The manager’s email must also exist in your Slack workspace. If no manager is set, no problem — only the owner gets invited.</p><p><em>If you work on a Slack Sandbox and a Trailhead Playground, you may have difficulties in setting a Manager and make email addresses match on both spaces, due to limitations. Don’t worry, and move on, some details explain later why it should still work.</em></p><h3>Step 5 — Activate the Flow</h3><p>The Flow ships in <strong>Draft</strong> status for safety.</p><p><strong>Setup → Flows → SSR Recipe 07 — Creation Channel Slack</strong></p><p>Review the entry criteria (Opportunity reaches <strong>Closed Won</strong>), then click <strong>Activate</strong>.</p><h3>Test the integration</h3><ol><li>Open (or create) an Opportunity with a linked <strong>Account</strong> and an <strong>owner</strong> whose email exists in Slack</li><li>Move it to <strong>Closed Won</strong> and save</li><li>Wait a few seconds — the callouts run asynchronously via the Queueable</li><li>Head to Slack: a new channel like #deal-acme-corp-2026 appears, the right people are members, and a welcome message is waiting:</li><li>Back on the Opportunity record, the <strong>Slack Channel Id</strong> field is now populated (read-only) — proof the full round-trip worked</li></ol><p>A fully provisioned deal room is created, zero manual clicks. If you are the Opp Owner, you’re invited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGaHszLNYHGw_649f_mUtQ.png" /><figcaption>Welcome!</figcaption></figure><h3>The details that make it production-ready</h3><p>A few design decisions worth highlighting — they’re what separate a demo from something you’d actually ship:</p><p><strong>Best-effort invitations.</strong> If the owner’s email exists in Slack but the manager’s doesn’t (or the manager field isn’t set), the channel is still created and the owner is still invited. A missing user never blocks the automation. No noisy errors, no half-broken flow.</p><p><strong>Idempotency.</strong> The Flow checks that SlackChannelId__c is empty before provisioning. If the Opportunity is edited again after closing, it won&#39;t spin up a duplicate channel. The stored ID <em>is</em> the &quot;already done&quot; flag.</p><p><strong>Silent lookups.</strong> users.lookupByEmail returning nothing simply skips that person. Great for resilience — but do enable Debug Logs during setup so you can see <em>why</em> someone wasn&#39;t invited (usually: their Salesforce email doesn&#39;t match the one they use in Slack).</p><h3>Troubleshooting</h3><p>No channel created =&gt; Bot has channels:manage? Token valid? Flow <strong>Active</strong>?</p><p>Channel created but nobody invited =&gt; Do Salesforce emails match Slack emails? Scope users:read.email added?</p><p>Manager not invited =&gt; Is the <strong>Manager</strong> field set on the owner&#39;s User record?</p><p>SlackChannelId__c stays empty =&gt; Check <strong>Apex Jobs</strong> and Debug Logs for the Queueable // Field not visible on the layout, add it to the page layout — FLS is read-only by design</p><h3>Need to customize the recipe?</h3><p>Here, we treat a “general” situation of closing deal. And of course, creating a Slack channel for each deal won is likely to make the feature unuseful and uncomfortable. As an admin, business analyst or developer/integrator, you may have some ideas to keep it easy to monitor.</p><ul><li>Don’t hesitate to tighten the conditions triggering the flow : you may want to track carefully specific accounts or specific deals, filtered by amounts, geographical data, etc.</li><li>think wisely about opportunity slips and teams ; your organization needs to be clean if you want right people to be invited in the channel</li></ul><h3>What’s next?</h3><p>Recipe 07 shows the SSR Stack doing more than notifications. It can <strong>orchestrate collaboration spaces</strong> directly from your CRM data. The pattern generalises: any Salesforce event can provision a Slack channel, invite the right people, and drop context in, automatically.</p><p>Coming up (and to be confirmed): support escalations with SLA-aware routing, quote approvals with interactive Slack buttons, AI-powered case summaries, and an Agentforce pipeline monitor.</p><p>The full repository, manifests, and all available recipes live on GitHub: 👉 <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">github.com/AlexandreKuzo/salesforce-slack-recipes</a></p><p><em>SSR Stack — Salesforce Slack Recipes. Feedback and PRs welcome.</em></p><p><a href="https://alexandrekuzo.com/">Alexandre</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=241b20b15706" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce × Slack — Build an “Opportunity Closed Won” Slack Alert with the SSR Stack (Recipe 02)]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/salesforce-slack-build-an-opportunity-closed-won-slack-alert-with-the-ssr-stack-recipe-02-fa300a4090a4?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa300a4090a4</guid>
            <category><![CDATA[salesforce-apex]]></category>
            <category><![CDATA[crm]]></category>
            <category><![CDATA[slack-api]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 10:50:04 GMT</pubDate>
            <atom:updated>2026-07-06T13:20:53.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2Ffqt2CMy_j_awz0tk3Rg.png" /></figure><p>Imagine your sales team wants to be notified every time an Opportunity reaches <strong>Closed Won</strong>.</p><p>Instead of asking users to constantly monitor Salesforce dashboards, why not send the information directly to Slack?</p><p>In this second SSR Stack recipe, we’ll build exactly that using Salesforce Flow and a reusable Apex service.</p><p>In this article, we’ll deploy <strong>Recipe 02</strong> of the SSR Stack, a reusable architecture built around Apex services, Flows, Custom Metadata and Slack.</p><p>For people who did not read the first article yet, here it is : <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8">https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8</a> ; it’s a comprehensive review of how to use it as a Salesforce Developer / Integrator.</p><p>Recipe n°2 is pretty simple, we are going to build specific Slack Alerts when Opportunities reach a specific stage ; it will be Closed Won for this one. Let’s see how installing it and playing with it.</p><p>After having completed steps written in the <a href="https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8">introduction article</a> please get into the following steps, we focus on the Salesforce side in this article.</p><p><strong>Step 1 — Clone the repo and deploy recipe 02</strong></p><p>After authorizing your org run this command in your terminal:</p><pre>sf project deploy start - manifest manifest/ssr-recipe02-package.xml - target-org my-org</pre><p><strong>Step 2 — Check the bot token is correctly configured and the recipe is deployed</strong></p><ul><li>In Salesforce Setup, search for Custom Settings</li><li>click SSR Slack Settings</li><li>check the Bot Token ; if you tried the SSR before, your bot token doesn’t need to be updated. If it’s the first time, paste the bot token you got from Slack when you created and installed your app</li><li>save</li></ul><p><strong>Step 3 — set a new record in the Custom Metadata Type SSR Slack Recipe</strong></p><ul><li>still in Salesforce Setup, search for custom Metadata types</li><li>click on SSR Slack Recipes =&gt; manage records</li><li>click on Edit for Recipe 02 — Alerte Changement Stage</li><li>set the channel ID you got from your Slack App ; if you created a new Slack channel, get the ID from the Slack App settings</li></ul><p><strong>Step 4 — Configure and activate the flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZ_3jgRpE9uOrukxhhkQCw.png" /></figure><ul><li>Open the SSR Recipe 02 — Alerte Changement Stage Flow</li><li>in the SSR Send Slack Message Action, set the Slack channel Id OR the field coming from the Custom Metadata Type SSR Slack Recipe</li><li>update your criteria for the triggering Opportunity : update the stage needed and add some quality requirements that can match what you are used to meet in corporate situations</li><li>save the flow</li></ul><p>Before testing, don’t forget to invite @YourBot to the channel !</p><p>Next, test the integration.</p><p>Open an opportunity in your sandbox. Here, we are going to pass an Opportunity at the closed Won stage. A few seconds later, the Slack notification appear.</p><p>A message is fired in Slack to illustrate the update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTR-eu71rRMzhV3Z2gy_-Q.png" /><figcaption>Boom!</figcaption></figure><p>Flexible and customizable in the flow, pushable to the channel you want, records accessible for people having the rights in Salesforce...</p><p>Integrating this feature should be straightforward. Don’t hesitate to adapt the scenario with new objects and use cases !</p><p>Thanks for reading, and stay tuned for recipe no. 03, which may be more ambitious.</p><p><a href="https://alexandrekuzo.com/"><strong>Alexandre</strong></a><strong> 🙂</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa300a4090a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce × Slack: Introducing the SSR Stack]]></title>
            <link>https://medium.com/@alexandre.kuzo_66025/salesforce-slack-introducing-the-ssr-stack-857057678cf8?source=rss-92b6fe7a5930------2</link>
            <guid isPermaLink="false">https://medium.com/p/857057678cf8</guid>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Alexandre Kuzo]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 15:57:47 GMT</pubDate>
            <atom:updated>2026-07-02T15:57:47.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3v1F1R8gJdp43jU3jiH0Ww.jpeg" /></figure><p>In 2021, Salesforce acquired Slack in its largest acquisition to date. Since then, Salesforce–Slack integrations have kept growing : new AppExchange packages, native setup wizards, and more recently, a “headless” push that puts Slack and several Salesforce apps at the forefront of the platform. That trend caught my attention, and I wanted to explore it hands-on.</p><h4><strong>Combining Slack and Salesforce is still harder than it looks</strong></h4><p>When you search for guides on setting up a Salesforce ↔ Slack integration, plenty of resources exist. But here is honest feedback from a Salesforce developer’s perspective:</p><p>- In a corporate context (contractor or employee), you often need **both** Salesforce Setup access **and** Slack workspace admin rights (or a friendly admin who will let you create a Slack sandbox ^^).</p><p>- Full end-to-end testing is not always straightforward in Salesforce sandboxes — for example, Trailhead Developer Edition orgs do not expose the Guided Slack Setup menu.</p><p>- Some native Slack × Salesforce features depend on specific licenses (Sales Cloud, Service Cloud, Slack Enterprise Grid, and so on). Those are powerful, but I cannot see how it looks.</p><p>I ran into all of this while trying to build something practical. Still, I was convinced it was possible to design a **maintainable, straightforward system** that connects both platforms without heavy native coupling. I had already integrated external systems with Salesforce orgs using Custom Settings, Remote Site Settings, Apex callouts, Flows, and Platform Events. Combining those building blocks seems enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qDYO7kyL0yknC5jfM2DQw.png" /><figcaption>I was stuck on this kind of screen on my Trailhead Playground</figcaption></figure><h4><strong>Presenting the SSR Stack</strong></h4><p>The <a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">SSR Stack</a> (for <strong>Salesforce Slack Recipes</strong>) is built for that purpose. It relies on patterns familiar to Salesforce admins and developers, and it is designed to be easy to deploy and test against a Slack Developer Sandbox.</p><p>Here is the use case we will walk through in this article (Recipe 01):</p><p>1. An Opportunity is created in Salesforce.</p><p>2. The Amount field is populated.</p><p>3. A Slack message is posted to a specific channel, including a link back to the record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5bwa4ufX5eA2TR5bvUV9A.png" /></figure><p>Simple? Useful? Absolutely! And a solid foundation for more advanced recipes (stage changes, case escalations, channel provisioning, AI summaries, Agentforce alerts, Logs observability…).</p><p>To try it, follow the plan below:</p><ul><li>Create a <a href="https://api.slack.com/developer-program">Slack Developer account</a> and spin up a Slack sandbox for testing.</li><li>Make sure you have admin access to a Salesforce org (<a href="https://trailhead.salesforce.com/fr">Trailhead</a> Developer Edition or a sandbox works fine).</li></ul><p>Then configure both sides.</p><h4><strong>Slack configuration</strong></h4><p>Once your Slack Developer account is ready, open “Your Apps” and click “Create New App” → “From scratch”. Give it a name (for example, `SSR Bot`) and select your development workspace.</p><p><strong>1. Install the app and retrieve the Bot Token</strong></p><p>Go to **Install App** in the left menu, then click **Install to Workspace**.</p><p>After installation, copy the **Bot User OAuth Token** (`xoxb-…`). You will need it in Salesforce — treat it like a password and never commit it to source control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF5YoZ6k0nhA-IKHKlVuoA.png" /><figcaption>Bot user Token : save it!</figcaption></figure><p><em>Note: for Recipe 01, you do NOT need Socket Mode. The SSR Stack sends outbound HTTP requests from Salesforce to the Slack Web API (`chat.postMessage`). Socket Mode is only required if your app must receive real-time events from Slack over a WebSocket.</em></p><p><strong>2. Add Bot Token Scopes</strong></p><p>Open “OAuth &amp; Permissions” → “Scopes” → “Bot Token Scopes”, and add:</p><ul><li>chat:write =&gt; so Bot can post messages in channels it’s invited in</li><li>channels:read =&gt; to access channels’ content</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrtDiySvogKldboyyR_DqQ.png" /><figcaption>Bot scopes</figcaption></figure><p>That is all you need for Recipe 01. (Later recipes may require additional scopes — for example, `channels:manage` for channel creation).</p><p>Reinstall the app if Slack prompts you to approve the new scopes.</p><p><strong>3. Create a channel and copy its ID</strong></p><p>In your Slack workspace, create a channel (for example, `#new-opportunities`).</p><p>To find the **Channel ID**:</p><p>1. Open the channel.</p><p>2. Click the channel name at the top → Integrations or channel details.</p><p>3. Scroll down — the Channel ID starts with `C` (for example, `C0123456789`).</p><p>Save this ID; you will paste it into Salesforce Custom Metadata in a moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*f9IPJjlCLBQMlFr6ffdWZg.png" /><figcaption>Channel ID down there</figcaption></figure><p><strong>4. Invite the bot to the channel</strong></p><p>In Slack, open your channel and run:</p><p>/invite or mention @YourAppName</p><p>The bot can only post to channels it has been invited to. This step is easy to forget — and the most common reason for a “silent” integration failure.</p><p><em>Note: I plan to add utility Apex classes to track logs in a custom object (like SysLogs) to catch errors if a step is missing in the configuration.</em></p><p><strong>Salesforce configuration</strong></p><p>This article targets developers or advanced admins comfortable deploying metadata. You will need:</p><ul><li>A Salesforce org authenticated in your environment.</li><li>The SSR Stack repository cloned locally.</li><li><a href="https://developer.salesforce.com/tools/salesforcecli">Salesforce CLI</a> installed.</li></ul><p>Authenticate your org if you have not already:</p><pre>sf org login web - alias my-org</pre><p>You can also run SFDX: Authorize an Org in VSCode.</p><p>Next deploy Recipe 01:</p><pre>sf project deploy start - manifest manifest/ssr-recipe01-package.xml - target-org my-org</pre><p>This command deploys everything required for the first recipe. The manifest is simply the list of metadata components Salesforce CLI pushes to your org. You can also use VSCode by reaching “SFDX: Deploy this source to Org”.</p><p>What gets deployed?</p><p>The manifest file deployed looks like this:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Package xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SlackApiMock&lt;/members&gt;<br>        &lt;members&gt;SlackCalloutQueueable&lt;/members&gt;<br>        &lt;members&gt;SlackInvocable&lt;/members&gt;<br>        &lt;members&gt;SlackInvocableTest&lt;/members&gt;<br>        &lt;members&gt;SlackService&lt;/members&gt;<br>        &lt;members&gt;SlackServiceTest&lt;/members&gt;<br>        &lt;name&gt;ApexClass&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SSR_Slack_Recipe__mdt&lt;/members&gt;<br>        &lt;members&gt;SSR_Slack_Settings__c&lt;/members&gt;<br>        &lt;name&gt;CustomObject&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SSR_Slack_Recipe.recipe_01&lt;/members&gt;<br>        &lt;name&gt;CustomMetadata&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SSR_Recipe01_Slack_Alert&lt;/members&gt;<br>        &lt;name&gt;Flow&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SSR_Slack_User&lt;/members&gt;<br>        &lt;name&gt;PermissionSet&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;types&gt;<br>        &lt;members&gt;SSR_Slack&lt;/members&gt;<br>        &lt;name&gt;RemoteSiteSetting&lt;/name&gt;<br>    &lt;/types&gt;<br>    &lt;version&gt;65.0&lt;/version&gt;<br>&lt;/Package&gt;</pre><p>Take a quick look on this:</p><ul><li><strong>Apex Classes : </strong>SlackService, SlackCalloutQueueable, SlackInvocable + tests =&gt; HTTP callouts to Slack; Flow entry point; async execution to avoid uncommitted-work errors</li><li><strong>SSR_Slack_Settings__c : </strong>Hierarchy Custom Setting, stores the Bot Token (`xoxb-…`) — configured in Setup, not in code</li><li><strong>SSR_Slack_Recipe__mdt : </strong>Custom Metadata Type, routes each recipe to a Slack Channel ID (“recipe_01”, “recipe_02”)</li><li><strong>SSR_Slack_Recipe.recipe_01 : </strong>Custom Metadata record, default routing record for Recipe 01 — update the Channel ID after deploy</li><li><strong>SSR_Recipe01_Slack_Alert : </strong>Record-Triggered Flow, fires on Opportunity creation and calls SlackInvocable</li><li><strong>SSR_Slack_User: </strong>Permission Set, Grants Apex + Custom Setting access to users who trigger the Flow</li><li><strong>SSR_Slack : </strong>Allows outbound HTTPS calls to “https://slack.com”</li></ul><p>You do <strong>not</strong> need to configure every of these components manually. Focus on the four steps below.</p><p><strong>Step 1 — Store the Bot Token</strong></p><p>1. In Salesforce Setup, search for “Custom Settings”</p><p>2. Click “SSR Slack Settings” → “Manage”.</p><p>3. Click “New” (org-level default).</p><p>4. Paste your `xoxb-…` token into “Bot Token”.</p><p>5. Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYQwR-MnKuvJ9Spe_JWUYA.png" /><figcaption>Custom setting entry point</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrorzofwLVUaKT68ATcKLw.png" /><figcaption>Location comes from your org linked to Trailhead, you can rename it.</figcaption></figure><p><strong>Step 2 — Set the Slack Channel ID</strong></p><p>1. In Setup, search for “Custom Metadata Types”.</p><p>2. Open “SSR Slack Recipe” → “Manage Records”.</p><p>3. Edit “Recipe 01 — Alerte Nouvelle Opportunite”.</p><p>4. Replace the placeholder “C0123456789” with your real Channel ID.</p><p>5. Ensure “Is Active” is checked and **Recipe Key** is `recipe_01`.</p><p>6. Save.</p><p><strong>This indirection is deliberate: Flows reference a recipeKey and not a hard-coded channel. You can change channels per environment without editing Flow logic.</strong></p><p><strong>Step 3 — Assign the Permission Set</strong></p><p>1. Setup → Permission Sets → SSR Slack User</p><p>2. Click Manage Assignments → Add Assignments</p><p>3. Assign it to your user (and any automation-running user if applicable).</p><p>Without this step, the Flow action will fail with an Apex access error.</p><p><strong>Step 4 — Activate the Flow</strong></p><p>The deployed Flow ships in Draft status.</p><p>1. Setup → Flows</p><p>2. Open SSR Recipe 01 — Alerte Nouvelle Opportunite</p><p>3. Review entry criteria (currently: Opportunity created, Amount not null)</p><p>4. Check if the Apex Action “SSR Send Slack Message” mentions recipe_01, set in Custom Metadata Type ; this will resolve the channelId</p><p>5. Click Activate</p><p><em>Optional: To match the “deals over $50,000” scenario, add in the flow an entry condition “Amount Greater than 50000” before activating. The current recipe fires on any Opportunity with an Amount value — a good default for testing, easy to tighten in Flow Builder.</em></p><p><strong>Test the integration</strong></p><p>1. In Salesforce, create a new Opportunity with an Amount (and a linked Account).</p><p>2. Wait a few seconds — the Apex callout runs asynchronously via SlackCalloutQueueable.</p><p>3. Check your Slack channel: you should see a message like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XShJYwKDyqyXosMxfIyoFw.png" /></figure><p><strong>4. Click the record link (if included) to confirm deep-linking works.</strong></p><p>If nothing appears in Slack, here is what to check:</p><p>No message at all =&gt; Bot invited to channel? Token saved in Custom Settings? Flow Active?</p><p>“not_in_channel” error (from Debug Logs) =&gt; Run invite @YourBot in the channel</p><p>“invalid_auth” (from Debug Logs) =&gt; Token copied correctly? Slack App reinstalled after scope change?</p><p>Flow never runs =&gt; Permission Set assigned? Entry criteria met (Amount populated)?</p><p>Apex error in Flow =&gt; User has “SSR_Slack_User”? Remote Site “SSR_Slack” active?</p><p>Enable Debug Logs for your user and filter on SlackService or SlackCalloutQueueable if you need to dig deeper.</p><p><strong>What about admins who do not use the CLI?</strong></p><p>This article focuses on CLI deployment because it matches the SSR Stack’s “as code” model (manifests, GitHub, incremental recipes). But admins have alternatives:</p><ul><li>“Change Sets” — deploy from a reference sandbox to another org via Setup (no terminal required).</li><li>“VS Code + Salesforce Extensions” — clone the repo, authorize an org, right-click → “Deploy Source to Org” (no Apex coding needed).</li><li>“Workbench” — possible with a pre-built ZIP, but not recommended as a primary path (security and ergonomics).</li></ul><p>Regardless of deployment method, post-deployment configuration is identical: Bot Token, Channel ID in Custom Metadata, Permission Set, Flow activation.</p><p><strong>What is next?</strong></p><p>Recipe 01 is the foundation. There is already is a recipe dealing with Opportunity stage alerts and the next to come tackles support escalations, quote approvals, Slack channel provisioning, OpenAI case summaries, or Agentforce pipeline monitor.</p><p>The full repository, manifests, and additional recipes are available on GitHub :</p><p><a href="https://github.com/AlexandreKuzo/salesforce-slack-recipes">https://github.com/AlexandreKuzo/salesforce-slack-recipes</a></p><p>If this walkthrough helped, please wait for the next articles. I’ll keep publishing on coming recipes, and a may dive deeper into how SlackInvocable and SlackCalloutQueueable work together.</p><p><em>Feedback and PRs welcome. Thank you for reading!</em></p><p><strong>Alexandre</strong> : <a href="https://alexandrekuzo.com/">https://alexandrekuzo.com/</a> 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=857057678cf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>