<?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 Kandeepan Yathuraj on Medium]]></title>
        <description><![CDATA[Stories by Kandeepan Yathuraj on Medium]]></description>
        <link>https://medium.com/@yathu2198?source=rss-a6f2aa303dee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9kXSTK8NzdroGKzgWhIgnQ.jpeg</url>
            <title>Stories by Kandeepan Yathuraj on Medium</title>
            <link>https://medium.com/@yathu2198?source=rss-a6f2aa303dee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:24:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yathu2198/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[Real-Time ITQuoter Sync with Webhooks, Azure Functions and PostgreSQL]]></title>
            <link>https://medium.com/@yathu2198/real-time-itquoter-sync-with-webhooks-azure-functions-and-postgresql-979d6a7b417f?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/979d6a7b417f</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[itquoter]]></category>
            <category><![CDATA[azure-blob]]></category>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 16:23:06 GMT</pubDate>
            <atom:updated>2026-12-02T11:11:21.275Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why We treat the webhook as a doorbell, not a delivery</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7993W6CoJPd9eQhJYLxrA.png" /><figcaption>Real-time ITQuoter sync: a webhook signals Azure Functions, which uses a queue and blob storage to update PostgreSQL</figcaption></figure><p>A salesperson changes a renewal in ITQuoter at 9:05 am. At 9:10 the account manager opens the dashboard, an integrated view that pulls data from several systems into one place, and it still shows yesterday’s value. It will keep showing it until the scheduled sync runs again.</p><h3>What is ITQuoter?</h3><p>ITQuoter is a cloud quoting and ordering platform for IT resellers and managed service providers. Sales teams build quotes there, turn them into sales orders, raise purchase orders to suppliers and track renewals, along with the accounts, contacts and opportunities behind them. For a lot of businesses, it’s where the day-to-day sales and ordering data is born.</p><p>That data rarely stays in one place. It feeds dashboards, reports and other systems, and those need to see changes quickly.</p><h3>The problem with a scheduled sync</h3><p>That dashboard got its ITQuoter data from a batch job. It pulled purchase orders, quotes and renewals from the ITQuoter API on a schedule and wrote them to the PostgreSQL database behind that dashboard. It was reliable, but between runs the data was stale, and people noticed.</p><p>ITQuoter can call a URL every time a record changes, so the fix sounded simple: listen to that webhook and update the database straight away. Getting it to work took a few hours. Getting it to work reliably took a few design decisions and a handful of surprises, and I’ll go through both so you don’t have to find the surprises yourself.</p><h3>What an ITQuoter webhook actually is</h3><p>An ITQuoter webhook is an HTTP POST that ITQuoter sends to your URL every time a record is created, changed or deleted.</p><p>To set one up:</p><ol><li>Click your profile.</li><li>Click <strong>Settings</strong>.</li><li>In the <strong>Integrations</strong> panel, click <strong>Other</strong>.</li><li>Open the <strong>Webhooks</strong> tab. You’ll see <strong>Webhook Setup</strong>.</li><li>In <strong>Enable</strong>, choose which changes to send. I use <strong>Create, Modify and Delete</strong>.</li><li>In <strong>Url</strong>, paste your endpoint’s URL and save.</li></ol><p>From then on, every save in ITQuoter sends one HTTP POST to that URL. It covers accounts, leads, contacts, prospects, account addresses, opportunities, quotes, renewals, order agreements, sales orders and purchase orders, so your endpoint has to handle (or politely ignore) all of them.</p><p>If you put a function key in that URL, treat it like a password: anyone who has the full URL can call your endpoint.</p><p>The settings page says the POST includes the module, the event type and the record IDs. The real request I captured looked like this (values made up):</p><pre>{<br>  &quot;event&quot;: &quot;purchase order.update&quot;,<br>  &quot;module&quot;: &quot;Purchase Orders&quot;,<br>  &quot;data&quot;: {<br>    &quot;orderID&quot;: &quot;3F2A9C10-0000-0000-0000-000000000001&quot;,<br>    &quot;poNumber&quot;: &quot;PO-10001&quot;,<br>    &quot;salesOrderID&quot;: &quot;-&quot;,<br>    &quot;status&quot;: 4<br>  }<br>}</pre><p>The event is &quot;&lt;record type&gt;.&lt;action&gt;&quot;, the module name is plural, and data holds the whole record, not just its ID. That last part caused my first real bug, which I’ll come back to.</p><h3>Five things that surprised me</h3><p>I learned these from real traffic, and each one changed the design.</p><ol><li><strong>The real webhook looked different from what the settings page describes.</strong> The page lists simple fields like “Module”, “Event Type” and “Record ID (numeric)”. The real request puts the whole record inside a data field, and the ID is a GUID with a different name for each type (orderID for purchase orders, renewalID for renewals). So I captured real webhooks first and wrote the code to match them, not the description.</li><li><strong>Every save fires an event</strong>, not only status changes. Attaching a file to a quote sends one too. One person working through a batch of quotes produced over a hundred events in a short burst.</li><li><strong>Payloads can be big.</strong> Because the whole record is included, a purchase order with many lines easily goes past 64 KB. Keep that number in mind.</li><li><strong>Module names aren’t stable.</strong> I saw both Purchase Order and Purchase Orders within a few days, so normalise them.</li><li><strong>The calls come from changing cloud IP addresses.</strong> I logged the caller IP of every request and saw several different addresses within seconds. An IP allow list wasn’t going to be reliable.</li></ol><h3>The design in one picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INVb0SrP7GU-0jY9oJQYLA.png" /><figcaption>Eight-step flow from an ITQuoter save, through a webhook, Azure Functions, a storage queue and blob, to PostgreSQL and the dashboard.</figcaption></figure><p>It’s two Azure Functions (.NET isolated worker), one Storage account and the database. The HTTP function receives the webhook, saves it and replies 200 straight away. The queue function does the real work in the background. Moreover, Here Blob Storage Means Azure Storage Container.</p><h3>Step 1: Reply fast, work later</h3><p>ITQuoter waits for your reply. If your endpoint calls the ITQuoter API, queries the database and writes three tables before it answers, a slow moment on your side becomes a timeout on theirs.</p><p>So the HTTP function does almost nothing. It reads the request, stores it and queues a message:</p><pre>[Function(&quot;ReceiveWebhook&quot;)]<br>public async Task&lt;ReceiveResult&gt; Run(<br>    [HttpTrigger(AuthorizationLevel.Function, &quot;post&quot;,<br>                 Route = &quot;webhooks/itquoter&quot;)] HttpRequestData req)<br>{<br>    var body     = await ReadCappedAsync(req.Body, maxBytes: 5 * 1024 * 1024);<br>    var eventId  = Guid.NewGuid();<br>    var blobName = $&quot;{DateTime.UtcNow:yyyy/MM/dd}/{eventId}.json&quot;;<br>    await payloads.UploadBlobAsync(blobName, BinaryData.FromString(body));<br><br>    return new ReceiveResult      // queue output binding + HTTP 200<br>    {<br>        Message  = JsonSerializer.Serialize(<br>                       new QueuedEvent(eventId, blobName)),<br>        Response = req.CreateResponse(HttpStatusCode.OK),<br>    };<br>}</pre><p>AuthorizationLevel.Function means every request needs the function key in the URL. Anything without it gets a 401 before my code runs.</p><p>The queue also gives you retries without writing any retry code. If processing fails because of a database blip or an API timeout, the message comes back and is tried again, up to 5 times. After the fifth failure it moves to a poison queue (&lt;queue&gt;-poison) instead of retrying forever or disappearing. And when a hundred events arrive at once, they wait in line instead of all hitting the database together.</p><h3>Step 2: The claim-check pattern (why there’s a blob)</h3><p>My first version put the whole webhook body on the queue. It worked in testing, then failed on a large purchase order.</p><p>An Azure Storage queue message can be at most 64 KB. Remember surprise #3? A big PO is bigger than that.</p><p>The fix is the claim-check pattern: store the large thing somewhere else and put a small ticket on the queue. The full payload goes to Blob Storage, one file per event, organised by date. The queue message carries only an event ID and the blob name. The processor reads the ticket, fetches the blob and carries on.</p><p>I keep every raw payload for 30 days (a storage lifecycle rule deletes older ones). That’s been very handy for debugging, because “what exactly did ITQuoter send at 10:42?” has a one-click answer.</p><h3>Step 3: Never trust the payload</h3><p>This decision made everything else simpler.</p><p>The payload contains the full record, so it’s tempting to write it straight to the database. I don’t. I treat the webhook as a doorbell, not a delivery.</p><p>A doorbell only tells you someone is at the door. It doesn’t hand you the parcel. In the same way, the ITQuoter webhook tells me a record changed. I don’t use the data inside the webhook (I keep it in the blob only for debugging). I take the record’s ID from it, go to the source, the ITQuoter API, and read the current record myself. That’s what gets stored.</p><pre>// Webhook says &quot;sales order X changed&quot;. Ask ITQuoter for it now.<br>// (the list endpoint, filtered to one record)<br>var id      = Uri.EscapeDataString(orderId);<br>var url     = $&quot;{baseUrl}/v1/sales_orders?orderID={id}&quot;;<br>var records = await GetListRecordsAsync(url);<br>await SalesOrdersTable.UpsertAsync(conn, records);</pre><p>The extra API call pays for itself. The same event arriving twice gives the same result. If an old “update” is retried after a newer one, it still fetches today’s data, so order doesn’t matter. A forged request can’t change anything either, because only what ITQuoter’s API returns gets written.</p><p>There’s one more benefit. The webhook reads from the same list endpoints the scheduled sync uses (?orderID=, ?quoteID=, ?renewalID=), so the two write identical rows and never overwrite each other with different values.</p><h3>Step 4: Upsert, and skip what didn’t change</h3><p>New records and updates take the same path: insert the row if it isn’t there, update it if it is. In PostgreSQL that’s ON CONFLICT:</p><pre>INSERT INTO sales_orders AS t (order_id, sales_order_number, status, raw_json)<br>SELECT r-&gt;&gt;&#39;orderID&#39;, r-&gt;&gt;&#39;salesOrderNumber&#39;, (r-&gt;&gt;&#39;status&#39;)::numeric, r<br>FROM jsonb_array_elements(@records) r<br>ON CONFLICT (order_id) DO UPDATE<br>SET sales_order_number = EXCLUDED.sales_order_number,<br>    status             = EXCLUDED.status,<br>    raw_json           = EXCLUDED.raw_json,<br>    updated_at         = now()<br>WHERE t.raw_json IS DISTINCT FROM EXCLUDED.raw_json; -- skip unchanged</pre><p>The last line is there because of surprise #2. Most of those hundred events change nothing I store, and I want updated_at to mean “the data changed”, not “I checked”.</p><p>Purchase orders get one extra guard. Two events for the same PO can arrive at the same moment, so the write takes a short per-PO lock (pg_advisory_xact_lock) and they run one after the other.</p><p>Deletes follow the same rule, because I don’t trust a “delete” event either. The processor asks ITQuoter whether the record still exists. If it’s gone, or comes back flagged as deleted, the row stays in the table, marked deleted with the date, so reports can still explain what happened to it.</p><h3>Step 5: Log every event</h3><p>Every webhook gets a row in an events table: when it arrived, the module, event type, record ID, the caller IP, and the outcome (Processed, Ignored, or Failed with the error and attempt count).</p><p>I didn’t expect this to be the most useful part, but it is. When someone asks “why didn’t my change show up?”, the answer is one query away:</p><pre>SELECT received_at, module, event_type, status, detail, error<br>FROM webhook_events<br>ORDER BY received_at DESC<br>LIMIT 20;</pre><p>It’s also how I found surprises #2, #4 and #5.</p><h3>Security without an IP allow list</h3><p>Because ITQuoter’s calls came from changing addresses, I didn’t rely on IP filtering. The protection comes in layers instead. Every request needs the function key, and a missing one gets a 401. A forged request that somehow had the key still couldn’t write anything, because the processor re-reads from the API. Bodies over 5 MB are rejected. The admin and deployment endpoints are restricted to the office network, separately from the public webhook URL. Secrets live in Key Vault and the app reads them with its managed identity, so there are no passwords in the app settings.</p><p>If ITQuoter offered a fixed list of outbound IPs or signed requests, I’d add that check too, and it’s worth asking your vendor about both.</p><h3>Hosting: App Service plan or Flex Consumption?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*AGxUrk7iTFVoRGlUblwFcw.png" /><figcaption>Comparison of the App Service plan and Flex Consumption for Azure Functions: billing, cold start, VNet support and when to choose each.</figcaption></figure><p>Both run the same code. The choice comes down to cost, cold starts and networking.</p><p>I used an App Service plan because one with spare capacity already existed, and the reporting database is only reachable on a private network, so VNet integration was a must. If you’re starting from zero, Flex Consumption is worth a look: it supports VNet integration and you only pay when webhooks arrive. Check that it’s available in your region before you commit.</p><p><em>My pick: if you already pay for an App Service plan with room to spare, use it. If you’re starting fresh, choose Flex Consumption.</em></p><h3>The result</h3><p>A change in ITQuoter now shows up in the reporting database within seconds instead of at the next scheduled run. Purchase orders, quotes, sales orders and renewals all follow the same pattern. The scheduled sync still runs as a safety net, so if a webhook is ever missed, the data catches up on the next run.</p><h3>The takeaway</h3><p>The webhook tells you that something changed. The API tells you what changed. I kept those two jobs separate: reply fast, queue a small ticket, re-read the record, upsert so repeats are harmless, and log every event. Most of the problems I expected from real-time sync, like duplicates, ordering and oversized payloads, never reached the database.</p><p>If you’re integrating ITQuoter, or any SaaS tool that sends webhooks, I’d start with the doorbell rule.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=979d6a7b417f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Design + UI Bakery: Better Dashboards, Fewer Tokens]]></title>
            <link>https://medium.com/@yathu2198/claude-design-ui-bakery-better-dashboards-fewer-tokens-f91f977a8279?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91f977a8279</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[uibakery]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[claude-design]]></category>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 17:52:37 GMT</pubDate>
            <atom:updated>2026-11-13T17:52:37.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32D1CdaWWDHaz9-k5qcgcw.jpeg" /><figcaption>Integrating Claude Design &amp; UI Bakery</figcaption></figure><p><em>How I stopped letting UI Bakery’s AI guess my design, and what I do now.<br></em>Look at these two rows of KPI cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WE0inCIxmh3HCKs-yqY32Q.jpeg" /></figure><p>The same tool built both. The same developer too, which is me. For the first row I typed a request into UI Bakery’s AI chat and took what came back. For the second row I designed the cards in Claude Design first, and then gave UI Bakery a prompt with the exact CSS.</p><p>The second way needed fewer rounds with UI Bakery’s AI. It also gave me cards I’m happy to put in front. This post is about how I work now, and where it still goes wrong.</p><p>One note about the pictures. Colombo Stock Exchange closing figures from Friday 13 November 2026, taken from <a href="https://economynext.com/sri-lanka-stocks-close-down-0-60-pct-dragged-by-hnb-and-lolc-290131/">EconomyNext</a>. The styling follows my sample cards for an example.</p><h3>What UI Bakery is, and what we use it for?</h3><p>UI Bakery is a low-code platform for building internal tools. Think dashboards, admin panels and report pages that sit on top of your own database and APIs.</p><p>It has an AI agent inside. You describe what you want in a chat box, and the agent writes the code into your app. In our app that means React pages and SQL actions.</p><p>I’m an automation developer at a managed service provider. We use UI Bakery for an internal web app where teams follow orders, renewals and reports. The data comes from PostgreSQL. Some of these reports lived in Power BI before, and we are moving them across.</p><p>The agent is not free to use. Every request spends tokens from our plan. That is the part of the bill I wanted to bring down.</p><h3>The old way: let the agent design it</h3><p>My old way was simple. Open the UI Bakery chat and type something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4YMLm9DZQyqXEKQmOE2DA.png" /><figcaption>Create a KPI card row…</figcaption></figure><p>With a request like that, the agent has to decide everything on its own. Card size. Font. Where the number sits. Which colour means trouble. And before it decides, it reads through the project to learn what is already there. I have watched it write “I’ll start by inventorying the tabs and their actions” and then open file after file. All of that reading and deciding is paid for.</p><p>The result is fine, but generic: grey numbers, a small icon, and no hint about which card needs attention. So I type “make the number bigger”, “add a status”, “no, not like that”. Each message is another round, and more tokens.</p><p>I was spending tokens twice. Once for the agent to guess the design, and again to correct the guess.</p><h3>What I do now: design in Claude Design first</h3><p>Now UI Bakery doesn’t design anything for me. The design happens in Claude Design, which is Claude’s design canvas, before UI Bakery hears about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIffcioOxpCrJZL54JVldw.png" /><figcaption>Two Tools, Two Jobs</figcaption></figure><ol><li><strong>Give Claude the app that already exists.</strong> I shared the code of the pages we had already built: the page files, the styles and the SQL actions. I added screenshots of the live pages too. Now Claude knows our colours, our fonts, how our tables and filters look, and how the code is laid out.</li><li><strong>Describe the new dashboard like I would to a colleague.</strong> I paste the requirement from the stakeholders. Claude Design builds a working preview on its canvas. It’s real HTML and CSS, and I can click through it.</li><li><strong>Argue with the preview, not with UI Bakery.</strong> “The green button doesn’t fit, make it white and blue.” “That tooltip is too much, plain text is enough.” “There is a big gap under the cards.” These rounds are quick, and none of them spends a UI Bakery token.</li><li><strong>Ask for the prompt.</strong> When the preview looks right, I ask Claude to write the UI Bakery prompt for it, with the real CSS values from the preview.</li></ol><p>By the time UI Bakery gets involved, the design questions are already answered. Its job is only to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZB_IZyDvpCVGq5j_BzW7FA.png" /><figcaption>Moving from design to production</figcaption></figure><h3>The prompt is a work order, not a wish</h3><p>This is the kind of prompt I paste into UI Bakery now. It’s the one behind the second row of cards in the pictures.</p><pre>KPI CARD ROW - market summary page only. Do not change other pages.<br>File: market-summary/kpi-cards.tsx<br><br>Container<br>- display: grid; 6 equal columns; no gap between cards<br>- background #FFFFFF; border 1px solid #E4E7EC; border-radius 12px<br><br>Each card<br>- padding 18px 20px 16px<br>- cards 2 to 6: border-left 1px solid #E4E7EC<br><br>Inside a card, top to bottom<br>- Label: 13px, weight 600, colour #1D2433, then an info icon (13px, #98A2B3)<br>- Value: 32px, weight 700, colour #101828, margin-top 10px<br>- Status pill on the same line as the value, right aligned:<br>  11px, weight 600, padding 3px 8px, border-radius 4px<br>    Up:   background #ECFDF3, text #067647<br>    Down: background #FEF3F2, text #B42318<br>- Sub-line: 12px, colour #667085, margin-top 22px</pre><p>Look at what is missing. There’s no “make it modern” and no “clean look”. Nothing in there needs interpreting. The agent doesn’t have to think about design at all, because there is no design left to think about.</p><p>Three lines go into almost every prompt I send:</p><ul><li><strong>A scope line.</strong> “This page only. Do not change other pages.” I work inside a large app, and I want the agent to stay on the page I’m changing.</li><li><strong>The file names.</strong> Claude has seen the code, so it can name the file to edit. The agent doesn’t need to search for it.</li></ul><h3>What came back</h3><p>Here are the two rows again, one above the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WE0inCIxmh3HCKs-yqY32Q.jpeg" /><figcaption>High-fidelity comparison: Row 01 represents UI Bakery’s standard, independent guess on design parameters. Row 02 shows the rich, unified result achievable when UI Bakery is guided with an exact CSS blueprint designed in Claude Design first.</figcaption></figure><p>The first row is the look I got from an earlier dashboard, where I only asked UI Bakery. The second row is the look from the new dashboard, where the design came from Claude. They are two different dashboards, so this isn’t a lab test. But the gap between them is the gap I see every time.</p><p>The new cards share one border, so the row reads as one summary. Every number has a status pill, and every card has a second line that explains the number.</p><p>UI Bakery could always build this. It builds what the prompt describes. My old prompts just didn’t describe much.</p><h3>When to use which</h3><p>UI Bakery’s AI has three modes. Fast is the cheapest, Smart is in the middle, and Thinking costs the most. With a prompt from Claude I always use Smart. For small things, like changing a word on a card, I use Fast and skip Claude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgSmTDV_Tns8x3McZDK0WQ.png" /><figcaption>UI Bakery’s three AI modes compared by token cost and how I split them: Fast handles small tweaks alone, while Smart executes the exact prompts generated by Claude.</figcaption></figure><p>I haven’t used Thinking mode in my development yet, because it uses a lot of tokens. So this table only compares the two modes I use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mX4sFlNYJlwxcY2Lke6cvw.png" /><figcaption>Task-by-task breakdown of when to pair Claude Design with UI Bakery versus when to let UI Bakery’s Fast or Smart mode handle simple edits and SQL tweaks on its own.</figcaption></figure><h3>Where the tokens went</h3><blockquote><strong><em>My estimate: 40 to 60% fewer UI Bakery tokens on new pages and components.</em></strong></blockquote><blockquote><em>On small changes, like a label or a column, the saving is close to zero.</em></blockquote><p>That figure is an estimate, not a measurement. UI Bakery doesn’t show me token use per dashboard, so I’m judging by how many rounds I no longer need. I still send fix prompts, and the exact prompt is longer than a vague one, which is why I don’t claim more.</p><p>I can tell you where the saving comes from, because I watched it happen.</p><ul><li><strong>No design guessing.</strong> The agent doesn’t spend tokens choosing sizes and colours. They are in the prompt.</li><li><strong>Fewer correction rounds.</strong> I already had the “no, not like that” conversation with the Claude preview. UI Bakery never sees it.</li><li><strong>Less searching.</strong> The prompt names the file. The agent doesn’t read half the project to find where the cards live.</li><li><strong>No testing I didn’t ask for.</strong> I test in the browser myself. I also stopped asking for a lint run across the whole project after every small change.</li></ul><p>One thing I should be clear about. The work didn’t disappear. It moved. Claude does the design thinking now, and Claude isn’t free either. For me the trade is worth it, because UI Bakery tokens were the tighter budget. Check your own plans before you copy me.</p><h3>Where it still goes wrong</h3><p><strong>It isn’t pixel-perfect every time.</strong> Most builds land close to the preview. Some don’t. Once the tooltips ended up hidden under the cards. Another time the cards came out looking different from the design. Each time I sent a small fix prompt for that one thing. That’s still cheaper than a redesign in chat, but “first try, every time” would be a lie.</p><p><strong>Claude can add its own assumptions.</strong> Once it put a business rule into the design that wasn’t in my requirement document. I caught it and took it out. Now I say it plainly at the start: no assumptions, only what’s in the requirement.</p><p><strong>Big rewrites are still big.</strong> Exact CSS helps with how a page looks. It doesn’t make a large data change small. For one performance change, the agent stopped halfway and told me it wouldn’t guess. I was glad it stopped. It was still not a cheap day.</p><p>The short version: decide the design where deciding is cheap, and use UI Bakery’s tokens for building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91f977a8279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetBox Explained: The Source of Truth Behind Modern Network Automation]]></title>
            <link>https://medium.com/@yathu2198/netbox-explained-the-source-of-truth-behind-modern-network-automation-2ccbced4cc2a?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ccbced4cc2a</guid>
            <category><![CDATA[netbox-labs]]></category>
            <category><![CDATA[box-net]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 11:21:21 GMT</pubDate>
            <atom:updated>2026-08-30T11:31:14.125Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked in network operations, you know the pain: an IP spreadsheet three people think is “the latest version,” a rack diagram nobody’s touched since 2019, and a config automation tool that only works if the inventory feeding it is actually correct. That last part is the catch — automation is only as good as the data behind it. For a long time, that data lived in scattered spreadsheets with no trustworthy home.</p><p>That’s the gap NetBox was built to close.</p><h3>What Is NetBox?</h3><p>NetBox is an open-source web application that acts as the <strong>Single Source of Truth (SSoT)</strong> for network infrastructure. It merges two things that used to live in separate tools:</p><ul><li><strong>DCIM</strong> (Data Center Infrastructure Management) — sites, racks, devices, cabling, power</li><li><strong>IPAM</strong> (IP Address Management) — prefixes, subnets, VLANs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3Ibv6f3Jb4f1DpG3OKo4A.png" /><figcaption>Fig 1 : The Core Pillars of NetBox: DCIM &amp; IPAM</figcaption></figure><p>Look up a device in NetBox and you can see its rack position, its interfaces, the IPs on those interfaces, the VLANs those IPs sit in, and the cable running to the next device — all connected, all queryable, all consistent.</p><h3>Why It Exists?</h3><p>Before tools like this existed, most teams stitched documentation together from whatever was on hand — inventories split across multiple spreadsheets, no vendor-neutral way to capture the <em>intended</em> state of the network. Update one file and forget another, and you get inconsistent documentation, broken topology records, and risky changes during maintenance. Worse, automation was nearly impossible to build on top of any of it, because the data was unstructured, incomplete, and not API-driven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*-RVbZoSNeXsz62tUmOm9_g.jpeg" /><figcaption>Fig 2 : Before Netbox</figcaption></figure><p>NetBox’s answer: give that data a real home — structured, validated, and reachable through an API.</p><h3>Three Design Principles Worth Knowing</h3><p><strong>1. Replicate the real world.</strong> The data model is strict on purpose. A classic example: IP addresses are assigned to <em>interfaces</em>, not to devices — because that’s how it actually works physically. Try to cable a fiber port into a copper port, and NetBox will refuse, because that connection doesn’t exist in reality either.</p><p><strong>2. Serve as a source of truth — intent before reality.</strong> NetBox is meant to hold the <em>intended</em> design of your network, like an architect’s blueprint, not a live mirror of whatever currently exists on the wire. The recommended workflow is: define it in NetBox first, then deploy it — not auto-import live data wholesale, which just imports your existing errors. Let a human validate the data first, and every downstream automation tool can trust NetBox completely instead of re-checking everything itself.</p><p><strong>3. Keep it simple.</strong> NetBox doesn’t try to become your DNS server, config deployment engine, or monitoring platform. It stays focused and exposes a powerful REST API so specialized tools can plug in and pull accurate data on demand.</p><h3>What NetBox Is <em>Not?</em></h3><p>It’s not a replacement for config management (Ansible, Nornir, Terraform), monitoring platforms (SolarWinds, PRTG), DNS/RADIUS servers, or facilities management systems. Its job is being the <strong>central repository</strong> that feeds accurate, vetted data to all of those tools via API — the conductor holding the sheet music so every other instrument plays from the same score.</p><h3>Why the Data Relationships Actually Matter?</h3><p>NetBox isn’t a flat list of assets — it’s a <strong>relational</strong> source of truth. Devices, IPs, and VLANs are interconnected nodes, deliberately modeled to reflect how infrastructure actually exists in the real world, not a convenient simplification of it.</p><p>That relational structure is what gives NetBox its data integrity. The hierarchy is enforced, not suggested: you can’t create a rack without a site, and you can’t create a device without a device type. Skip a dependency and the object simply won’t save. That rigidity can feel like friction the first time you hit it, but it’s the whole point — it’s the mechanism that keeps bad data from ever entering the system.</p><p>And this is exactly why it matters for automation. Clean API queries depend on structured relationships; if the underlying data is inconsistent, your automation outcomes will be too. A script that pulls “all devices in Site X, filtered by role, with their assigned prefixes” only works reliably because those relationships were enforced at creation time, not patched together after the fact.</p><h3>The Device Creation Flow</h3><p>This is where the philosophy stops being abstract and becomes something you click through — and it’s the part that trips up newcomers most, because NetBox won’t let you create a device in isolation. Everything has a required order, built around a simple rule: <strong>prerequisites must exist first, dependent objects come after.</strong></p><p><strong>Prerequisites — must create first:</strong></p><ul><li><strong>Site</strong> — the location a device belongs to</li><li><strong>Manufacturer</strong> — must exist before a device type can reference it</li><li><strong>Device Type</strong> — depends on the manufacturer; defines the model, rack height, and interface templates</li><li><strong>Device Role</strong> — what the device actually does: access switch, core router, firewall</li></ul><p><strong>Mandatory fields on the device record itself:</strong></p><ul><li><strong>Site</strong></li><li><strong>Device Type</strong></li><li><strong>Device Role</strong></li><li><strong>Status</strong></li></ul><p>Everything else — including the device’s name — is a common optional field you fill in as your data matures.</p><p><strong>The dependency flow, in order:</strong></p><ol><li>Create Site</li><li>Create Manufacturer</li><li>Create Device Type</li><li>Create Device Role</li><li>Create Device</li></ol><p>That last point surprises people every time: you can save a valid device in NetBox without naming it. The four mandatory fields are the only things NetBox insists you can’t guess or skip — because a site, a role, a type, and a status are the minimum facts needed to say “this real thing exists somewhere.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2hLZ20Jyn-MeGEC4x9FSQ.png" /><figcaption>Fig 3 : Device Creation Mind Map</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mP4c3_o4dxX47p5f0F3lQ.png" /><figcaption>Fig 4 : Device Creation Order</figcaption></figure><h3>Strategic Planning: Don’t Build as You Learn</h3><p>The most common mistake teams make with NetBox isn’t a data-modeling error — it’s skipping the planning step entirely. A few principles worth internalizing before you start architecting:</p><ul><li><strong>Understand before you architect.</strong> Learn NetBox’s full feature scope before committing to a design. Building as you learn leads to massive rework later, once you discover a feature you needed three layers of hierarchy ago.</li><li><strong>Collaborate across teams.</strong> Gather requirements from NetOps, SecOps, and DevOps, and collect the object details each of them actually needs mapped. Just as important: explicitly decide what NetBox <em>will not</em> store, so the source-of-truth boundary stays clean.</li><li><strong>Standardize early.</strong> Strict naming conventions, applied consistently across regions, sites, and roles, are what keep the data usable at scale.</li><li><strong>Design for scale now.</strong> Ask the uncomfortable question up front: will this model still hold up if the number of data centers doubles?</li></ul><h3>A Practitioner’s Note</h3><p>Where this really pays off is when NetBox stops being manual data entry and becomes the target of an automated sync. In multi-vendor environments — SD-WAN controllers, cloud-managed Wi-Fi, firewall management planes, and RMM tools all reporting overlapping infrastructure — the hard part isn’t calling five different vendor APIs. It’s reconciling five different data shapes into one canonical device lifecycle and pushing it into NetBox without violating its dependency rules. Get that right, and NetBox becomes exactly what it promises: something every other tool in your stack can query and trust without double-checking.</p><h3>Getting Data In</h3><ul><li><strong>Manual (UI):</strong> fine for small setups or early validation.</li><li><strong>Python:</strong> the <strong>pynetbox</strong> library wraps NetBox’s REST API into simple Python calls — the standard for scripted automation.</li><li><strong>Other languages (C#, etc.):</strong> NetBox’s API is plain REST with token auth, so any language that can make HTTP calls can push data the same way pynetbox does underneath.</li></ul><p>All three follow the same rule: authenticate, respect the creation order, let NetBox reject anything that breaks the model.</p><h3>The Takeaway</h3><p>NetBox earns its “source of truth” label by being strict where it matters — enforced relationships and a creation order that mirrors physical reality — and deliberately narrow where it doesn’t, leaving DNS, monitoring, and config deployment to tools built for those jobs. If your automation isn’t sitting on top of a system like this, you’re not really automating — you’re running scripts against a guess.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ccbced4cc2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Targeted Power BI Data as a Styled HTML Table to Outlook via Power Automate?]]></title>
            <link>https://medium.com/@yathu2198/how-to-send-targeted-power-bi-data-as-a-styled-html-table-via-power-automate-c6c06ab993c9?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6c06ab993c9</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[power-automate]]></category>
            <category><![CDATA[power-bi-tutorials]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[microsoft-power-automate]]></category>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 14:22:52 GMT</pubDate>
            <atom:updated>2026-04-14T01:58:24.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CooDIHtXBU1xiUrHsgMDA.png" /><figcaption>8-step blueprint: Automating Power BI data directly into Outlook.</figcaption></figure><p>Many business users don’t open dashboards every day. In domains such as <strong>network operations</strong>, <strong>finance</strong>, and <strong>banking</strong>, operational teams often prefer to <strong>receive filtered, priority‑based ticket data automatically by email at a fixed time each day</strong>.</p><p>Whether it’s <strong>network incident tickets (P1/P2 outages)</strong>, <strong>banking system alerts</strong>, <strong>risk or compliance tickets</strong>, or <strong>financial operations exceptions</strong>, teams need <strong>only the most critical information</strong> delivered directly to their inbox — without logging into dashboards or navigating reporting tools.</p><p>This article explains how to build a <strong>daily scheduled email</strong> that:</p><ul><li>Queries Power BI data</li><li>Converts it into a clean HTML table</li><li>Sends it automatically once per day</li><li>Works correctly with Outlook and email signatures</li></ul><h3>◆ Business Scenario: Daily Operational Ticket Report (Network, Finance &amp; Banking)</h3><p>Assume you manage operations for a <strong>network operations center (NOC)</strong>, <strong>financial services platform</strong>, or <strong>banking systems team</strong>.<br> Every morning, operational managers want a <strong>daily Outlook email</strong> showing:</p><ul><li>Active <strong>P1 / P2 tickets</strong> (network outages, system incidents, critical transaction issues)</li><li>Affected <strong>systems, applications, or services</strong></li><li>Current <strong>ticket status and priority</strong>, without logging into Power BI dashboards</li></ul><p>Instead of asking teams to open reports or monitoring tools, we’ll build a <strong>Scheduled Cloud Flow</strong> that runs <strong>once per day</strong> and automatically emails <strong>only the filtered, high‑priority ticket data</strong>.</p><h3>🧩 Solution Overview</h3><p>Here’s the pattern we’ll implement:<br>1. Scheduled Cloud Flow (Daily)<br>2.Run a query against a dataset <br>3.Extract rows <br>4.Map ticket fields for email<br>5.Create HTML table <br>6.Apply scoped CSS styling <br>7. Decode HTML <br>8. Send Outlook email</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcdMlpEvyHlWrdZ0H67K8w.png" /></figure><p><strong>✅ Step 1: Create a Scheduled Cloud Flow (Daily)</strong></p><ol><li>Go to <strong>Power Automate</strong></li><li>Click <strong>Create</strong></li><li>Select <strong>Scheduled cloud flow</strong></li><li>Configure:</li></ol><ul><li><strong>Flow name</strong>: Preferred Name</li><li><strong>Start time</strong>: e.g. 08:00 AM</li><li><strong>Repeat every</strong>: 1</li><li><strong>Frequency</strong>: Day</li></ul><p>5.Click <strong>Create</strong></p><p>✅ This ensures the flow runs <strong>once every day automatically</strong>.</p><p><strong>✅ Step 2: Run a Query Against a Power BI Dataset</strong></p><p>Add the action:<br><strong>Power BI → Run a query against a dataset<br></strong>Select:</p><ul><li>Workspace</li><li>Dataset</li></ul><p>Example DAX Query (Organization Operations Use Case)</p><pre>EVALUATE<br>FILTER(<br>    Operations_Tickets,<br>    Operations_Tickets[Priority] IN { &quot;P1&quot;, &quot;P2&quot; }<br>        &amp;&amp; Operations_Tickets[Status] = &quot;Active&quot;<br>)</pre><p>This returns only <strong>active high‑priority issues</strong>, such as delivery delays or supply shortages affecting restaurants.</p><p><strong>✅ Step 3: Extract the Rows Array<br></strong>We only need the rows.<br>Add a <strong>Compose</strong> action:</p><pre>outputs(&#39;Run a query against a dataset&#39;)?[&#39;body&#39;]?[&#39;tables&#39;][0]?[&#39;rows&#39;]</pre><p>✅ Step 4: Map Ticket Fields for Email (Select Action)</p><p>This step reshapes raw dataset columns into <strong>email‑friendly field names</strong>.<br>Add a <strong>Select</strong> action.</p><p><strong>From</strong></p><pre>Outputs of Step 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*h_U4UPXzRbEuaArMlvFvuA.png" /><figcaption>This mapping ensures that only <strong>relevant, readable fields</strong> are included in the email.</figcaption></figure><p>✅ Step 5: Create the HTML Table<br>Add <strong>Create HTML table</strong>.</p><ul><li><strong>From</strong>: Output of <strong>Select</strong></li><li><strong>Columns</strong>: Automatic</li></ul><p>✅ Step 6: Apply Outlook‑Safe Styling</p><p>Outlook email signatures use HTML tables.<br> Global CSS will break them.</p><pre>&lt;style&gt;<br>  .ticket-table {<br>    border-collapse: collapse;<br>    width: 100%;<br>    font-family: Arial, Helvetica, sans-serif;<br>    font-size: 13px;<br>  }<br>  .ticket-table th {<br>    background-color: #c4d600;<br>    color: #000000;<br>    border: 1px solid #2e7d32;<br>    padding: 8px;<br>    text-align: left;<br>  }<br>  .ticket-table td {<br>    border: 1px solid #dddddd;<br>    padding: 8px;<br>  }<br>&lt;/style&gt;<br><br>&lt;p style=&quot;font-family: Arial, Helvetica, sans-serif; font-size: 14px; margin-bottom: 10px;&quot;&gt;<br>  &lt;strong&gt;P1 / P2 Active Incident Tickets&lt;/strong&gt;&lt;br/&gt;<br>  &lt;span style=&quot;color:#555;&quot;&gt;<br>    Report generated on<br>    @{formatDateTime(convertTimeZone(utcNow(), &#39;UTC&#39;, &#39;Sri Lanka Standard Time&#39;), &#39;dd MMM yyyy HH:mm&#39;)}<br>    (Sri Lanka Time)<br>  &lt;/span&gt;<br>&lt;/p&gt;<br>@{replace(body(&#39;Build_Tickets_HTML_Table___&#39;),&#39;&lt;table&gt;&#39;,&#39;&lt;table class=&quot;ticket-table&quot;&gt;&#39;)}</pre><p>✅ Step 7: Decode HTML Before Sending<br>Power Automate encodes HTML by default.<br>Add a <strong>Compose</strong> action:</p><pre>replace(<br>  replace(<br>    replace(<br>      replace(<br>        outputs(&#39;Format Email HTML Content&#39;),<br>        &#39;&amp;lt;&#39;, &#39;&lt;&#39;<br>      ),<br>      &#39;&amp;gt;&#39;, &#39;&gt;&#39;<br>    ),<br>    &#39;&amp;quot;&#39;, &#39;&quot;&#39;<br>  ),<br>  &#39;&amp;#39;&#39;, &#39;&#39;&#39;&#39;<br>)</pre><p><strong>✅ Step 8: Send the Email</strong></p><p>Add <strong>Send an email (V2)</strong>.</p><ul><li><strong>Body</strong>: Output of decoded HTML</li><li>Configure recipients and subject</li><li>Save the flow</li></ul><p>✅ Email is sent <strong>automatically once per day</strong>.</p><h3>🔹 Key Takeaways</h3><ul><li>Scheduled Cloud Flows are ideal for daily reporting</li><li>Power BI datasets can be queried directly</li><li>Mapping fields improves clarity and reuse</li><li>Outlook requires scoped CSS</li><li>HTML decoding is required once before sending</li><li>Email is often the most effective delivery channel for operational data</li></ul><p><a href="https://www.linkedin.com/in/kandeepan-yathuraj/">https://www.linkedin.com/in/kandeepan-yathuraj/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6c06ab993c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Week 11: Book Nation Goes Live! A Full-Stack Milestone in Our E-commerce Journey]]></title>
            <link>https://medium.com/@yathu2198/week-11-book-nation-goes-live-a-full-stack-milestone-in-our-e-commerce-journey-d31134c3eebf?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/d31134c3eebf</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Mon, 19 May 2025 05:11:42 GMT</pubDate>
            <atom:updated>2025-05-19T05:11:42.523Z</atom:updated>
            <content:encoded><![CDATA[<p>This week marks an exciting turning point: the <strong>frontend of the BookNation project is officially live</strong> and publicly accessible. After weeks of backend setup, feature development, and refining API logic, it’s incredibly rewarding to see the <strong>real product</strong> come together on screen.</p><p>📚💻 <a href="https://booknation-one.vercel.app/">Visit the Live Site</a><br> <em>(Note: Backend deployment is currently in progress!)</em></p><h3>⚙️ Project Overview: MERN Stack E-commerce App</h3><p>Our project is a full-stack, multi-vendor <strong>e-commerce platform for books</strong>. Customers can browse, view details, add books to their cart or wishlist, and place orders. Sellers have their own login, can manage listings, track orders, and view earnings.</p><p>The tech stack includes:</p><ul><li><strong>MongoDB</strong> — NoSQL database for managing users, products, orders, and messages</li><li><strong>Express.js</strong> — API routes and business logic</li><li><strong>React.js </strong>— Fast, component-based frontend experience</li><li><strong>Node.js</strong> — Backend server and API handling</li></ul><h3>✅ Week 11 Highlights</h3><h3>🖥️ Frontend Launch (Vite + Redux Toolkit)</h3><p>After carefully wiring up API integrations and managing application state using <strong>Redux Toolkit</strong>, the <strong>customer-facing bookstore frontend is now LIVE</strong> on Vercel!</p><h3>🌟 Key Features</h3><ul><li>🔍 <strong>Browse Books</strong> — View all listed books with pricing, authors, and ratings</li><li>📦 <strong>Product Detail Page</strong> — See individual book details including images, description, seller info, and customer reviews</li><li>❤️ <strong>Wishlist &amp; Cart Functionality</strong> — Add or remove books from your wishlist and cart with real-time state updates</li><li>🔐 <strong>Authentication</strong> — Customers can log in or register securely</li><li>📑 <strong>Order Workflow (Coming Soon)</strong> — Once the backend is deployed, order placement and history tracking will go live</li></ul><h3>🔄 Backend Progress &amp; API Integration</h3><p>On the backend side, we’ve created fully functional API endpoints with <strong>role-based authentication</strong> and <strong>MongoDB-based data models</strong> for:</p><ul><li>📚 Product Management</li><li>🛒 Cart and Wishlist Handling</li><li>📬 Messaging System</li><li>📈 Seller Dashboards</li><li>💳 Order Management</li><li>🧾 Transactions</li></ul><p>We used <strong>JWT for token-based authentication</strong>, implemented secure route protection, and validated user inputs throughout.</p><p>APIs like /api/product, /api/user, /api/cart, /api/order, and /api/wallet are all tested locally and integrated with the frontend using <strong>Axios</strong>.</p><p>🛠️ The backend is currently being prepared for deployment and will be launched shortly to fully support the live frontend functionality.</p><h3>🌐 End-to-End Feature Flow (Soon to Be Fully Live)</h3><p>Once backend deployment is complete, customers will enjoy a seamless full-stack experience:</p><h3>👤 Customer Flow:</h3><ul><li>Register or log in</li><li>Browse all books or search by category/keyword</li><li>View detailed book pages</li><li>Add to wishlist or cart</li><li>Place orders and track them</li></ul><h3>🛍️ Seller Flow (Already in development):</h3><ul><li>Add/edit book listings</li><li>Manage inventory</li><li>View order statuses</li><li>Track wallet and sales</li></ul><h3>🌟 Key Learnings This Week</h3><ul><li><strong>React makes frontend development faster and cleaner</strong>, especially with hot module reloading and minimal config</li><li>Using <strong>Redux Toolkit</strong> simplifies state management and scales well with multi-page applications</li><li>Splitting backend into <strong>modular controllers and route files</strong> improved maintainability</li><li>Syncing the frontend with token-protected APIs using Axios interceptors is a must for real-world apps</li></ul><h3>🔮 Next Steps</h3><p>🚧 <strong>Deploy Backend</strong> — Finalize server deployment with proper environment variable management and hosting</p><p>📱 <strong>Improve Mobile Responsiveness</strong> — Enhance the frontend UI for better experience on phones and tablets</p><h3>🧩 Conclusion</h3><p>Week 11 was a <strong>game-changing milestone</strong> — moving from isolated local testing to a <strong>live, accessible product</strong>.</p><p>The frontend of our bookstore is ready for the world, and soon, once the backend is deployed, customers will enjoy the <strong>full shopping experience</strong>. Building this from the ground up has been an incredible learning experience in full-stack architecture, React integration, and production readiness.</p><p>Stay tuned for more updates as we move toward complete deployment! 🚀</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d31134c3eebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Seller Dashboard – Book Nation — Week 10]]></title>
            <link>https://medium.com/@yathu2198/building-the-seller-dashboard-book-nation-week-10-b6bbf620888b?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6bbf620888b</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sun, 18 May 2025 13:12:25 GMT</pubDate>
            <atom:updated>2025-05-18T13:12:25.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building the Seller Dashboard – Book Nation — Week 10</h3><p>In Week 10 of my MERN stack e-commerce project, I focused on developing a comprehensive <strong>Seller Dashboard</strong> — a crucial feature that gives sellers a quick overview of their business performance. The dashboard pulls together multiple data points such as total sales, orders, pending deliveries, recent messages, and more.</p><p>This post will walk you through the full-stack implementation — including the <strong>React dashboard UI</strong>, <strong>Redux integration</strong>, and the <strong>backend API</strong> that makes it all work seamlessly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4YsEETdmC8YeX-VRnZAkA.png" /></figure><h3>🎯 Key Features of the Seller Dashboard</h3><p>The seller dashboard is designed to be both <strong>informative</strong> and <strong>user-friendly</strong>, providing quick access to:</p><ul><li>📊 Total Sales</li><li>📦 Total Products</li><li>🧾 Total Orders</li><li>⏳ Pending Orders</li><li>📃 Recent Orders</li></ul><p>These insights are shown using summary cards, a dynamic chart, a recent messages panel, and a latest orders table.</p><h4>🔧 Backend Implementation</h4><h4>✅ API Route</h4><pre>router.get(&#39;/seller/get-dashboard-data&#39;, authMiddleware, dashboardController.get_seller_dashboard_data);</pre><p>🧠 Controller Logic</p><pre>get_seller_dashboard_data = async (req, res) =&gt; {<br>    const { id } = req;<br>    try {<br>        const totalSale = await sellerWallet.aggregate([<br>            { $match: { sellerId: { $eq: id } } },<br>            { $group: { _id: null, totalAmount: { $sum: &#39;$amount&#39; } } }<br>        ]);<br><br>        const totalProduct = await productModel.find({ <br>          sellerId: new ObjectId(id) <br>        }).countDocuments();<br><br>        const totalOrder = await authOrder.find({ <br>          sellerId: new ObjectId(id) <br>        }).countDocuments();<br><br>        const totalPendingOrder = await authOrder.find({<br>            $and: [<br>                { sellerId: new ObjectId(id) },<br>                { delivery_status: &#39;pending&#39; }<br>            ]<br>        }).countDocuments();<br><br>        const messages = await sellerCustomerMessage.find({<br>            $or: [<br>                { senderId: id },<br>                { receverId: id }<br>            ]<br>        }).limit(3);<br><br>        const recentOrders = await authOrder.find({<br>            sellerId: new ObjectId(id)<br>        }).limit(5);<br><br>        responseReturn(res, 200, {<br>            totalProduct,<br>            totalOrder,<br>            totalPendingOrder,<br>            messages,<br>            recentOrders,<br>            totalSale: totalSale.length &gt; 0 ? totalSale[0].totalAmount : 0<br>        });<br>    } catch (error) {<br>        console.log(error.message);<br>    }<br>};</pre><h4>💻 Frontend Dashboard (React + Redux)</h4><h4>🔄 Data Fetching with Redux</h4><p>In the seller dashboard component, I used useEffect to dispatch an action that fetches data from the backend:</p><pre>useEffect(() =&gt; {<br>  dispatch(get_seller_dashboard_data());<br>}, []);</pre><p>📦 Data Stored in Redux</p><pre>const {<br>  totalSale,<br>  totalOrder,<br>  totalProduct,<br>  totalPendingOrder,<br>  recentOrder,<br>  recentMessage,<br>} = useSelector((state) =&gt; state.dashboardData);</pre><h3>🚀 Challenges Faced</h3><ul><li>Efficiently aggregating seller wallet data using MongoDB’s $group.</li><li>Filtering pending orders and messages with $and and $or conditions.</li><li>Balancing backend efficiency with frontend responsiveness.</li></ul><h3>🧠 Final Thoughts</h3><p>This dashboard brings everything together for sellers — making it easy to manage and monitor store performance. Integrating backend aggregation, Redux state management, and real-time UI elements helped me appreciate the power of <strong>full-stack development</strong>.</p><p>Let me know if you’d like to see a code breakdown, UI screenshots, or a GitHub repo preview!</p><p>📆 What’s Next?</p><p>Here’s a glimpse of what’s lined up for Week 11:<br>🔹 Final Preparations and Launch</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><p>Thanks for reading — stay tuned for the Week 11 update!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6bbf620888b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‍ Handling Sellers -Book Nation -Week 9]]></title>
            <link>https://medium.com/@yathu2198/handling-sellers-book-nation-week-9-3495c2d4cbaf?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/3495c2d4cbaf</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sun, 18 May 2025 12:59:20 GMT</pubDate>
            <atom:updated>2025-05-18T12:59:20.355Z</atom:updated>
            <content:encoded><![CDATA[<p>In this Week 9 update of my MERN stack e-commerce project <strong>Book Nation</strong>, I focused on implementing <strong>seller management for admins</strong>, a crucial feature for maintaining platform integrity and operational oversight.</p><p>After completing the order management system in Week 8, the next natural step was to give the admin tools to <strong>oversee sellers</strong>, view overall platform activity, and track key business metrics through a <strong>centralized dashboard</strong>.</p><h3>🎯 Why Seller Management is Important</h3><p>A healthy e-commerce platform relies on responsible sellers. Giving admins the ability to monitor seller performance, sales, and activities ensures:</p><ul><li>Better trust between buyers and sellers.</li><li>Prevention of spam, fraud, or inactive vendor accounts.</li><li>Transparency in platform-wide metrics for decision-making.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUySHKnHSWyQGDBmeySprw.png" /></figure><h3>🛠️ Backend: Admin Dashboard Route</h3><p>To empower the admin with insights, I created a protected route to fetch platform statistics and seller details.</p><pre>router.get(&#39;/admin/get-dashboard-data&#39;, authMiddleware, dashboardController.get_admin_dashboard_data);</pre><h3>📊 Controller Logic: Fetching Admin Insights</h3><p>The get_admin_dashboard_data method aggregates multiple collections — orders, products, sellers, messages, and wallet transactions — to produce a snapshot of the platform&#39;s performance.</p><pre>class dashboardController {<br>  get_admin_dashboard_data = async (req, res) =&gt; {<br>    try {<br>      const totalSale = await myShopWallet.aggregate([<br>        {<br>          $group: {<br>            _id: null,<br>            totalAmount: { $sum: &#39;$amount&#39; }<br>          }<br>        }<br>      ]);<br><br>      const totalProduct = await productModel.countDocuments();<br>      const totalOrder = await customerOrder.countDocuments();<br>      const totalSeller = await sellerModel.countDocuments();<br>      const messages = await adminSellerMessage.find({}).limit(3);<br>      const recentOrders = await customerOrder.find({}).limit(5);<br><br>      responseReturn(res, 200, {<br>        totalProduct,<br>        totalOrder,<br>        totalSeller,<br>        messages,<br>        recentOrders,<br>        totalSale: totalSale.length &gt; 0 ? totalSale[0].totalAmount : 0<br>      });<br><br>    } catch (error) {<br>      console.log(error.message);<br>    }<br>  };<br>}</pre><h3>🧠 Redux Toolkit: Fetching Dashboard Data (Async Thunk)</h3><p>To pull admin dashboard data into the frontend, I created an <strong>asynchronous thunk</strong> using createAsyncThunk. This allows for easy API calling, state tracking (loading, success, error), and integration with Redux Toolkit.</p><pre>export const get_admin_dashboard_data = createAsyncThunk(<br>  &#39;dashboard/get_admin_dashboard_data&#39;,<br>  async (_, { rejectWithValue, fulfillWithValue }) =&gt; {<br>    try {<br>      const { data } = await api.get(&#39;/admin/get-dashboard-data&#39;, {<br>        withCredentials: true<br>      });<br>      return fulfillWithValue(data);<br>    } catch (error) {<br>      return rejectWithValue(error.response.data);<br>    }<br>  }<br>);</pre><h4>🔍 Key Concepts:</h4><ul><li>createAsyncThunk: Automatically generates pending, fulfilled, and rejected action types for cleaner async handling.</li><li>withCredentials: true: Ensures cookies/session tokens are sent with the request for authentication.</li><li>fulfillWithValue(data): Gracefully returns the successful response.</li><li>rejectWithValue(error.response.data): Handles and sends structured error messages.</li></ul><p>This async thunk is consumed in the Redux dashboardSlice, allowing the admin dashboard to <strong>reactively display</strong> data once fetched.</p><h3>🚧 Challenges &amp; Solutions</h3><h4>🚧 Challenge: Aggregating Seller Earnings</h4><p>🔍 <strong>Solution</strong>: Used MongoDB’s $group and $sum aggregation to calculate total income from the wallet collection.</p><h4>🚧 Challenge: Multiple Asynchronous Queries</h4><p>🔍 <strong>Solution</strong>: Used await consistently for reliable execution order and proper error handling.</p><h4>🚧 Challenge: Displaying Real-Time Metrics</h4><p>🔍 <strong>Solution</strong>: Structured the API to return the latest data on every request — allowing the admin dashboard to reflect real-time updates.</p><h4>🚧 Challenge: Optimizing Data Fetch</h4><p>🔍 <strong>Solution</strong>: Limited heavy collections like messages and orders to a few recent items using .limit(n) for performance.</p><h4>✅ Summary</h4><p>This week’s feature focused on <strong>admin control and platform health monitoring</strong> by:</p><ul><li>Building a secure route for fetching seller and sales data.</li><li>Aggregating platform metrics like total orders, products, and earnings.</li><li>Creating a dynamic dashboard UI for a better admin experience.</li><li>Laying the foundation for future admin features like seller verification, performance analytics, and dispute resolution.</li></ul><p>📆 What’s Next?</p><p>Here’s a glimpse of what’s lined up for Week 10:<br>🔹 Seller Dashboard Implementation</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><p>Thanks for reading — stay tuned for the Week 10 update!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3495c2d4cbaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Handling Customer Orders -Book Nation - Week 8]]></title>
            <link>https://medium.com/@yathu2198/handling-customer-orders-book-nation-week-8-8bd9d024a08b?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd9d024a08b</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sun, 18 May 2025 04:20:30 GMT</pubDate>
            <atom:updated>2025-05-18T04:20:30.237Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll walk you through what I worked on during <strong>Week 8</strong> of my MERN stack e-commerce project, <strong>Book Nation</strong>. After successfully implementing the <strong>ratings and reviews system</strong> in Week 7, this week I focused on building a core part of any e-commerce platform — <strong>managing customer orders</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CDO4Z3BU0_oTFky4-w_QgA.png" /></figure><p>This feature enables users to place orders for books in their cart and lets them view their past orders, while also allowing admins or sellers to track and manage those orders effectively.</p><h3>💡 Why Order Management Matters</h3><p>Order management is the backbone of e-commerce. It allows:</p><ul><li><strong>Customers</strong> to finalize purchases and view past order details.</li><li><strong>Admins/Sellers</strong> to process, track, and fulfill orders.</li></ul><p>Without this, no shopping platform can function beyond browsing and carting.</p><h3>🛠️ Backend: Order Model (Mongoose)</h3><p>To store orders in <strong>MongoDB</strong>, I created a schema that captures essential details like books ordered, user ID, total price, status, payment method, and timestamps.</p><pre>const { Schema, model } = require(&#39;mongoose&#39;);<br><br>const orderSchema = new Schema({<br>  userId: {<br>    type: Schema.ObjectId,<br>    required: true,<br>    ref: &#39;users&#39;<br>  },<br>  books: [<br>    {<br>      bookId: {<br>        type: Schema.ObjectId,<br>        ref: &#39;books&#39;,<br>        required: true<br>      },<br>      quantity: {<br>        type: Number,<br>        required: true<br>      }<br>    }<br>  ],<br>  totalPrice: {<br>    type: Number,<br>    required: true<br>  },<br>  paymentMethod: {<br>    type: String,<br>    enum: [&#39;Cash on Delivery&#39;, &#39;Card&#39;],<br>    default: &#39;Cash on Delivery&#39;<br>  },<br>  status: {<br>    type: String,<br>    enum: [&#39;Pending&#39;, &#39;Processing&#39;, &#39;Shipped&#39;, &#39;Delivered&#39;, &#39;Cancelled&#39;],<br>    default: &#39;Pending&#39;<br>  },<br>  orderedAt: {<br>    type: Date,<br>    default: Date.now<br>  }<br>}, { timestamps: true });<br><br>module.exports = model(&#39;orders&#39;, orderSchema);</pre><h4>🔗 Backend Routes &amp; Controllers</h4><h4>✅ Placing an Order</h4><pre>router.post(&#39;/customer/place-order&#39;, orderController.place_order);</pre><pre>place_order = async (req, res) =&gt; {<br>  const { userId, books, totalPrice, paymentMethod } = req.body;<br><br>  try {<br>    await orderModel.create({<br>      userId,<br>      books,<br>      totalPrice,<br>      paymentMethod<br>    });<br><br>    responseReturn(res, 201, {<br>      message: &quot;Order Placed Successfully&quot;<br>    });<br>  } catch (error) {<br>    console.log(error.message);<br>  }<br>};</pre><p>📄 Fetching Order History]</p><pre>router.get(&#39;/customer/orders/:userId&#39;, orderController.get_orders);</pre><pre>get_orders = async (req, res) =&gt; {<br>  const { userId } = req.params;<br><br>  try {<br>    const orders = await orderModel.find({ userId })<br>      .populate(&#39;books.bookId&#39;, &#39;title author price coverImage&#39;)<br>      .sort({ createdAt: -1 });<br><br>    responseReturn(res, 200, { orders });<br>  } catch (error) {<br>    console.log(error.message);<br>  }<br>};</pre><h4>🖥️ Frontend: Orders.jsx Component</h4><p>This component allows users to view their previous orders in a clean, readable UI.</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import { get_customer_orders } from &#39;../store/reducers/orderReducer&#39;;<br><br>const Orders = () =&gt; {<br>  const dispatch = useDispatch();<br>  const { userInfo } = useSelector(state =&gt; state.auth);<br>  const { orders } = useSelector(state =&gt; state.order);<br><br>  useEffect(() =&gt; {<br>    if (userInfo?._id) {<br>      dispatch(get_customer_orders(userInfo._id));<br>    }<br>  }, [userInfo]);<br><br>  return (<br>    &lt;div className=&quot;py-10 px-4 md:px-16&quot;&gt;<br>      &lt;h2 className=&quot;text-2xl font-semibold text-slate-700 mb-6&quot;&gt;My Orders&lt;/h2&gt;<br>      &lt;div className=&quot;space-y-6&quot;&gt;<br>        {orders.map((order, index) =&gt; (<br>          &lt;div key={index} className=&quot;p-4 border rounded-md shadow-md bg-white&quot;&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Order ID: {order._id}&lt;/p&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Status: {order.status}&lt;/p&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Total: Rs. {order.totalPrice}&lt;/p&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Payment: {order.paymentMethod}&lt;/p&gt;<br>            &lt;div className=&quot;mt-2 grid grid-cols-1 sm:grid-cols-2 gap-3&quot;&gt;<br>              {order.books.map((item, idx) =&gt; (<br>                &lt;div key={idx} className=&quot;flex items-center gap-3&quot;&gt;<br>                  &lt;img src={item.bookId.coverImage} className=&quot;w-16 h-20 object-cover&quot; /&gt;<br>                  &lt;div&gt;<br>                    &lt;h3 className=&quot;font-medium text-slate-800&quot;&gt;{item.bookId.title}&lt;/h3&gt;<br>                    &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Qty: {item.quantity}&lt;/p&gt;<br>                    &lt;p className=&quot;text-sm text-gray-600&quot;&gt;Author: {item.bookId.author}&lt;/p&gt;<br>                  &lt;/div&gt;<br>                &lt;/div&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Orders;</pre><h3>🚧 Challenges &amp; Solutions</h3><h4>🚧 Challenge: Storing Complex Order Data</h4><p>🔍 <strong>Solution:</strong> Used an embedded subdocument array in MongoDB to store multiple books under a single order, each with its quantity.</p><h4>🚧 Challenge: Ensuring Authenticated Checkout</h4><p>🔍 <strong>Solution:</strong> Checked userInfo state in Redux to ensure the user is logged in before allowing order placement. Otherwise, redirect to login page.</p><h4>🚧 Challenge: Viewing Order History</h4><p>🔍 <strong>Solution:</strong> Created a get_orders controller that populates book details using .populate() and sorts by most recent orders.</p><h4>🚧 Challenge: Real-Time Order Status Tracking</h4><p>🔍 <strong>Solution:</strong> Added a status field in the order schema with enums for tracking progress — can later be updated by the admin dashboard.</p><h4>🚧 Challenge: Clean and Responsive UI</h4><p>🔍 <strong>Solution:</strong> Used Tailwind CSS for layout, flex/grid for responsive design, and appropriate spacing to make the order history visually appealing.</p><h3>✅ Summary</h3><p>This week’s implementation of the order management system showcases how to:</p><ul><li>Design a flexible <strong>order schema</strong> with embedded book data</li><li>Securely handle <strong>order creation</strong> and <strong>order history</strong></li><li>Use <strong>Redux Toolkit</strong> to manage global state and async actions</li><li>Provide users with a clean, responsive <strong>order history view</strong></li><li>Prepare for future admin features like <strong>status updates</strong> and <strong>order filtering</strong></li></ul><p>📆 What’s Next?</p><p>Here’s a glimpse of what’s lined up for Week 9:<br>🔹 Handling Sellers by Admin</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><p>Thanks for reading — stay tuned for the Week 9 update!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd9d024a08b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⭐ Giving Ratings & Reviews for Books — Week 7]]></title>
            <link>https://medium.com/@yathu2198/giving-ratings-reviews-for-books-week-7-44fbe9f08402?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/44fbe9f08402</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sat, 17 May 2025 12:56:23 GMT</pubDate>
            <atom:updated>2025-05-17T12:56:23.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>⭐ Giving Ratings &amp; Reviews for Books — Week 7</h3><p>In this post, I’ll walk you through what I worked on during <strong>Week 7</strong> of my MERN stack e-commerce project, <strong>Book Nation</strong>. After implementing the <strong>shopping cart</strong> and <strong>wishlist</strong> in Week 6, this week I focused on building an important feature for user engagement and trust — <strong>ratings and reviews for books</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*gIWf2I_wuAlA3-zxj5LnLA.png" /></figure><p>This feature allows customers to rate and write reviews for the books they’ve purchased, giving future buyers insight into quality, content, and reader satisfaction.</p><h3>📚 Why Book Reviews Matter</h3><p>In any book-selling platform, <strong>reviews are essential</strong>. They help readers:</p><ul><li>Evaluate the quality and readability of a book</li><li>Understand the experiences of other readers</li><li>Make informed buying decisions</li></ul><p>For sellers, reviews also provide feedback that can help in curating better selections and improving service.</p><h3>🛠️ Backend: Book Review Model</h3><p>To store reviews in MongoDB, I created a <strong>Mongoose schema</strong> specifically for <strong>book reviews</strong>. Each review is associated with a bookId and stores the reviewer&#39;s name, rating, review text, and the date.</p><pre>const { Schema, model } = require(&quot;mongoose&quot;);<br><br>const reviewSchema = new Schema({<br>    bookId: {<br>        type: Schema.ObjectId,<br>        required: true<br>    },<br>    name: {<br>        type: String,<br>        required: true<br>    },<br>    rating: {<br>        type: Number,<br>        default: 0<br>    },<br>    review: {<br>        type: String,<br>        required: true<br>    },<br>    date: {<br>        type: String,<br>        required: true<br>    }<br>}, { timestamps: true });<br><br>module.exports = model(&#39;reviews&#39;, reviewSchema);</pre><h3>🔗 Routes: Submitting &amp; Fetching Book Reviews</h3><p>I created two routes to manage the review process:</p><pre>// Submit a book review<br>router.post(&#39;/customer/submit-review&#39;, homeControllers.submit_review);<br><br>// Get all reviews for a specific book<br>router.get(&#39;/customer/get-reviews/:bookId&#39;, homeControllers.get_reviews);</pre><ul><li>The submit-review route is called when a customer posts a new review.</li><li>The get-reviews route fetches all reviews for a particular book, using its bookId.</li></ul><h3>📥 Submitting a Review (POST)</h3><p>When a user submits a review, this controller handles it:</p><pre>submit_review = async (req, res) =&gt; {<br>    const { bookId, rating, review, name } = req.body;<br><br>    try {<br>        await reviewModel.create({<br>            bookId,<br>            name,<br>            rating,<br>            review,<br>            date: moment(Date.now()).format(&#39;LL&#39;)<br>        });<br><br>        // Recalculate average rating for the book<br>        let totalRating = 0;<br>        const reviews = await reviewModel.find({ bookId });<br><br>        reviews.forEach(r =&gt; totalRating += r.rating);<br><br>        const averageRating = reviews.length ? (totalRating / reviews.length).toFixed(1) : 0;<br><br>        await bookModel.findByIdAndUpdate(bookId, {<br>            rating: averageRating<br>        });<br><br>        responseReturn(res, 201, {<br>            message: &quot;Review Added Successfully&quot;<br>        });<br><br>    } catch (error) {<br>        console.log(error.message);<br>    }<br>}</pre><h3>📤 Fetching Reviews (GET with Pagination + Analytics)</h3><p>The get_reviews method fetches paginated reviews and also returns a summary breakdown of how many users gave 5, 4, 3, 2, or 1 star:</p><pre>get_reviews = async (req, res) =&gt; {<br>    const { bookId } = req.params;<br>    let { pageNo } = req.query;<br>    pageNo = parseInt(pageNo);<br>    const limit = 5;<br>    const skipPage = limit * (pageNo - 1);<br><br>    try {<br>        let getRating = await reviewModel.aggregate([<br>            {<br>                $match: {<br>                    bookId: new ObjectId(bookId),<br>                    rating: { $not: { $size: 0 } }<br>                }<br>            },<br>            { $unwind: &quot;$rating&quot; },<br>            {<br>                $group: {<br>                    _id: &quot;$rating&quot;,<br>                    count: { $sum: 1 }<br>                }<br>            }<br>        ]);<br><br>        let rating_review = [<br>            { rating: 5, sum: 0 },<br>            { rating: 4, sum: 0 },<br>            { rating: 3, sum: 0 },<br>            { rating: 2, sum: 0 },<br>            { rating: 1, sum: 0 }<br>        ];<br><br>        for (let i = 0; i &lt; rating_review.length; i++) {<br>            for (let j = 0; j &lt; getRating.length; j++) {<br>                if (rating_review[i].rating === getRating[j]._id) {<br>                    rating_review[i].sum = getRating[j].count;<br>                    break;<br>                }<br>            }<br>        }<br><br>        const totalReviews = await reviewModel.countDocuments({ bookId });<br>        const reviews = await reviewModel.find({ bookId })<br>            .skip(skipPage)<br>            .limit(limit)<br>            .sort({ createdAt: -1 });<br><br>        responseReturn(res, 200, {<br>            reviews,<br>            totalReview: totalReviews,<br>            rating_review<br>        });<br><br>    } catch (error) {<br>        console.log(error.message);<br>    }<br>}</pre><p>✅ <strong>What it returns</strong>:</p><ul><li>5 paginated reviews</li><li>Total number of reviews</li><li>Summary of how many reviews exist for each rating (1–5 stars)</li></ul><p>📦 <strong>Component: </strong><strong>Reviews.jsx</strong></p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import Rating from &#39;./Rating&#39;; // Displays average star rating<br>import RatingTemp from &#39;./RatingTemp&#39;; // Displays fixed star count for each row (1 to 5 stars)<br>import Pagination from &#39;./Pagination&#39;; // Handles review pagination<br>import { Link } from &#39;react-router-dom&#39;; // For conditional navigation to login<br>import RatingReact from &#39;react-rating&#39;; // Star rating input<br>import { FaStar } from &#39;react-icons/fa&#39;; // Filled star icon<br>import { CiStar } from &#39;react-icons/ci&#39;; // Empty star icon<br>import { useDispatch, useSelector } from &#39;react-redux&#39;; // Redux hooks<br>import { customer_review, get_reviews, messageClear, product_details } from &#39;../store/reducers/homeReducer&#39;; // Async thunk actions<br>import toast from &#39;react-hot-toast&#39;; // Notification messages</pre><h3>🔍 Purpose: Importing required modules:</h3><ul><li>UI components, Redux actions/selectors, and utility libraries used in the review functionality.</li></ul><p>🧠 <strong>Component Logic &amp; Local State</strong></p><pre>const Reviews = ({ product }) =&gt; {<br>    const dispatch = useDispatch();<br><br>    const [parPage, setParPage] = useState(10); // Reviews per page<br>    const [pageNumber, setPageNumber] = useState(1); // Current page</pre><ul><li>parPage defines how many reviews to show per page.</li><li>pageNumber keeps track of the current pagination page.</li></ul><pre>    const { userInfo } = useSelector(state =&gt; state.auth); // Get logged-in user<br>    const { successMessage, reviews, rating_review, totalReview } = useSelector(state =&gt; state.home); // Reviews state</pre><p>Selects required Redux state:</p><ul><li>userInfo: For authentication check</li><li>reviews: List of reviews</li><li>rating_review: Distribution of ratings (1–5 stars)</li><li>totalReview: Total number of reviews</li><li>successMessage: Success feedback after review submission</li></ul><p>📝 <strong>Handle Review Submission</strong></p><pre>    const review_submit = (e) =&gt; {<br>        e.preventDefault();<br>        const obj = {<br>            name: userInfo.name,<br>            review: re,<br>            rating: rat,<br>            productId: product._id<br>        };<br>        dispatch(customer_review(obj)); // Dispatch thunk to submit review<br>    };</pre><p>🔁 <strong>useEffect: Post-Submission Workflow</strong></p><pre>    useEffect(() =&gt; { <br>        if (successMessage) {<br>            toast.success(successMessage); // Show toast if review submitted<br>            dispatch(get_reviews({ productId: product._id, pageNumber })); // Refresh reviews<br>            dispatch(product_details(product.slug)); // Refresh product rating<br>            setRat(&#39;&#39;); setRe(&#39;&#39;); // Reset form inputs<br>            dispatch(messageClear()); // Clear successMessage in Redux<br>        }  <br>    }, [successMessage]);</pre><p>When a review is successfully submitted:</p><ul><li>Shows toast</li><li>Refreshes reviews and product data</li><li>Clears input fields</li><li>Clears message state</li></ul><p>⭐ <strong>Rating Bar Graph</strong></p><pre>&lt;div className=&#39;flex gap-2 flex-col py-4&#39;&gt;<br>  {[5,4,3,2,1].map((val, i) =&gt; (<br>    &lt;div key={val} className=&#39;flex justify-start items-center gap-5&#39;&gt;<br>      &lt;div className=&#39;text-md flex gap-1 w-[93px]&#39;&gt;<br>        &lt;RatingTemp rating={val} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&#39;w-[200px] h-[14px] bg-slate-200 relative&#39;&gt;<br>        &lt;div style={{ width: `${Math.floor((100 * (rating_review[i]?.sum || 0)) / totalReview)}%` }} className=&#39;h-full bg-[#Edbb0E]&#39;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;p className=&#39;text-sm text-slate-600&#39;&gt;{rating_review[i]?.sum || 0}&lt;/p&gt;<br>    &lt;/div&gt;<br>  ))}<br>&lt;/div&gt;</pre><p>💡 <strong>Display User Reviews</strong></p><pre>&lt;h2 className=&#39;text-slate-600 text-xl font-bold py-5&#39;&gt;Product Review ({totalReview})&lt;/h2&gt;<br>&lt;div className=&#39;flex flex-col gap-8 pb-10 pt-4&#39;&gt;<br>  {reviews.map((r, i) =&gt; (<br>    &lt;div key={i} className=&#39;flex flex-col gap-1&#39;&gt;<br>      &lt;div className=&#39;flex justify-between items-center&#39;&gt;<br>        &lt;div className=&#39;flex gap-1 text-xl&#39;&gt;<br>          &lt;RatingTemp rating={r.rating} /&gt;<br>        &lt;/div&gt;<br>        &lt;span className=&#39;text-slate-600&#39;&gt;{r.date}&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;span className=&#39;text-slate-600 text-md&#39;&gt;{r.name}&lt;/span&gt;<br>      &lt;p className=&#39;text-slate-600 text-sm&#39;&gt;{r.review}&lt;/p&gt;<br>    &lt;/div&gt;<br>  ))}</pre><h4>🚧 Challenge: Fetching &amp; Displaying Product-Specific Reviews</h4><p>🔍 <strong>Solution:</strong> Used useEffect() to dispatch get_reviews() and fetch reviews based on the product ID and current page number. This ensures reviews are dynamically loaded per product and paginated correctly.</p><h4>🚧 Challenge: Submitting New Reviews Securely</h4><p>🔍 <strong>Solution:</strong> Created a controlled form to capture the user’s rating and review. On submission, the data is dispatched through customer_review() and Redux updates the backend and state.</p><h4>🚧 Challenge: Managing Review State Across the App</h4><p>🔍 <strong>Solution:</strong> Leveraged Redux Toolkit to handle asynchronous logic (fetching, submitting reviews), global state management (homeReducer), and messageClear() to reset success messages cleanly after actions.</p><h4>🚧 Challenge: Recalculating Ratings After Submission</h4><p>🔍 <strong>Solution:</strong> After a successful review submission, used Redux actions get_reviews() and product_details() inside a useEffect() to fetch updated reviews and refresh the average rating and breakdown in real-time.</p><h4>🚧 Challenge: Rating Distribution Visualization</h4><p>🔍 <strong>Solution:</strong> Mapped through the rating_review array to display a dynamic rating histogram (5 stars to 1 star) using progress bars and a custom RatingTemp component for visual clarity.</p><h4>🚧 Challenge: Authentication-Based Form Rendering</h4><p>🔍 <strong>Solution:</strong> Checked userInfo from Redux to conditionally render the review form. If the user is not logged in, a login prompt is displayed instead of the form.</p><h4>🚧 Challenge: Paginating Reviews Efficiently</h4><p>🔍 <strong>Solution:</strong> Implemented a custom Pagination component and maintained pageNumber and parPage state locally. Updates reviews dynamically on page change.</p><h4>🚧 Challenge: Responsive and Clean UI</h4><p>🔍 <strong>Solution:</strong> Built with Tailwind CSS to ensure a mobile-first, responsive layout. Used utility classes for clean spacing, typography, and layout with flex and grid where needed.</p><p>📆 What’s Next?</p><p>Here’s a glimpse of what’s lined up for Week 8:<br>🔹 book orders management</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><p>Thanks for reading — stay tuned for the Week 8update!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44fbe9f08402" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Cart and Wishlist Features for Book Nation — Week 6]]></title>
            <link>https://medium.com/@yathu2198/building-the-cart-and-wishlist-features-for-book-nation-week-6-4ea41b0b8b00?source=rss-a6f2aa303dee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea41b0b8b00</guid>
            <dc:creator><![CDATA[Kandeepan Yathuraj]]></dc:creator>
            <pubDate>Sat, 17 May 2025 11:21:42 GMT</pubDate>
            <atom:updated>2025-05-17T11:29:05.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building the Cart and Wishlist Features for Book Nation — Week 6</h3><p>In this post, I’ll walk you through what I worked on during <strong>Week 6</strong> of my MERN stack e-commerce project, <strong>Book Nation</strong>. After implementing the seller profile image upload feature in Week 5, this week I focused on developing two core features every e-commerce platform needs: the <strong>shopping cart</strong> and the <strong>wishlist</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7kS0wylzHKXYn-EgPStwMg.png" /></figure><p>These features enhance the user experience by letting customers save items they’re interested in and manage their purchases easily.</p><pre>const cartController = require(&#39;../../controllers/home/cartController&#39;)<br>const router = require(&#39;express&#39;).Router()<br><br>router.post(&#39;/home/product/add-to-cart&#39;, cartController.add_to_cart)<br>router.get(&#39;/home/product/get-cart-product/:userId&#39;, cartController.get_cart_products)<br>router.delete(&#39;/home/product/delete-cart-product/:cart_id&#39;, cartController.delete_cart_products)<br>router.put(&#39;/home/product/quantity-inc/:cart_id&#39;, cartController.quantity_inc)<br>router.put(&#39;/home/product/quantity-dec/:cart_id&#39;, cartController.quantity_dec)<br><br>router.post(&#39;/home/product/add-to-wishlist&#39;, cartController.add_wishlist)<br>router.get(&#39;/home/product/get-wishlist-products/:userId&#39;, cartController.get_wishlist)<br>router.delete(&#39;/home/product/remove-wishlist-product/:wishlistId&#39;, cartController.remove_wishlist)<br><br>module.exports = router</pre><p>In this code snippet from the Book Nation backend, I set up Express.js routes to manage the cart and wishlist features of the application. Each route connects to a specific controller function that handles the required operation. For the cart, users can add products (POST /add-to-cart), fetch their cart items (GET /get-cart-product/:userId), delete products (DELETE /delete-cart-product/:cart_id), and increase or decrease product quantities (PUT /quantity-inc/:cart_id and PUT /quantity-dec/:cart_id). For the wishlist, users can add products (POST /add-to-wishlist), view all wishlist items (GET /get-wishlist-products/:userId), and remove items (DELETE /remove-wishlist-product/:wishlistId). This setup ensures smooth RESTful communication between frontend and backend, enabling dynamic user interaction with their cart and wishlist</p><pre>const cartModel = require(&#39;../../models/cartModel&#39;)<br>const { responseReturn } = require(&#39;../../utiles/response&#39;)<br>const { mongo: {ObjectId}} = require(&#39;mongoose&#39;)<br>const wishlistModel = require(&#39;../../models/wishlistModel&#39;)<br><br>class cartController{<br>   <br>    add_to_cart =  async(req, res) =&gt; {<br>        const { userId, productId, quantity } = req.body<br>        try {<br>            const product = await cartModel.findOne({<br>                $and: [{<br>                    productId : {<br>                        $eq: productId<br>                    }<br>                },<br>                {<br>                    userId: {<br>                        $eq: userId<br>                    }<br>                }<br>            ]<br>            })<br><br>            if (product) {<br>                responseReturn(res,404,{error: &quot;Book is Already Added To Cart&quot; })<br>            } else {<br>                const product = await cartModel.create({<br>                    userId,<br>                    productId,<br>                    quantity<br>                })<br>                responseReturn(res,201,{message: &quot;Added To Cart Successfully&quot; , product})<br>            }<br>            <br>        } catch (error) {<br>            console.log(error.message)<br>        }<br>    }<br>    // End Method <br><br>    get_cart_products = async(req, res) =&gt; {<br>       const co = 5;<br>       const {userId } = req.params<br>       try {<br>        const cart_products = await cartModel.aggregate([{<br>            $match: {<br>                userId: {<br>                    $eq: new ObjectId(userId)<br>                }<br>            }<br>        },<br>        {<br>            $lookup : {<br>                from: &#39;products&#39;,<br>                localField: &#39;productId&#39;,<br>                foreignField: &quot;_id&quot;,<br>                as: &#39;products&#39;<br>            }<br>        } <br>      ])<br>      let buy_product_item = 0<br>      let calculatePrice = 0;<br>      let cart_product_count = 0;<br>      const outOfStockProduct = cart_products.filter(p =&gt; p.products[0].stock &lt; p.quantity)<br>      for (let i = 0; i &lt; outOfStockProduct.length; i++) {<br>         cart_product_count = cart_product_count + outOfStockProduct[i].quantity        <br>      }<br>      const stockProduct = cart_products.filter(p =&gt; p.products[0].stock &gt;= p.quantity)<br>      for (let i = 0; i &lt; stockProduct.length; i++) {<br>        const { quantity } = stockProduct[i]<br>        cart_product_count = buy_product_item + quantity<br><br>        buy_product_item = buy_product_item + quantity<br>        const { price,discount } = stockProduct[i].products[0]<br>        if (discount !== 0) {<br>            calculatePrice = calculatePrice + quantity * (price - Math.floor((price * discount) / 100 ))<br>        } else {<br>            calculatePrice  = calculatePrice + quantity * price<br>        }        <br>      } // end for<br>      let p = []<br>      let unique = [...new Set(stockProduct.map(p =&gt; p.products[0].sellerId.toString()))] <br>      for (let i = 0; i &lt; unique.length; i++) {<br>        let price = 0;<br>        for (let j = 0; j &lt; stockProduct.length; j++) {<br>           const tempProduct = stockProduct[j].products[0]<br>           if (unique[i] === tempProduct.sellerId.toString()) {<br>                let pri = 0;<br>                if (tempProduct.discount !== 0) {<br>                    pri = tempProduct.price - Math.floor((tempProduct.price * tempProduct.discount) / 100 )<br>                } else {<br>                    pri = tempProduct.price<br>                }<br>        pri = pri - Math.floor((pri * co) / 100)<br>        price = price + pri * stockProduct[j].quantity<br>        p[i] = {<br>            sellerId: unique[i], <br>            shopName: tempProduct.shopName,<br>            price,<br>            products: p[i] ? [<br>                ...p[i].products,<br>                {<br>                    _id: stockProduct[j]._id,<br>                    quantity: stockProduct[j].quantity,<br>                    productInfo: tempProduct <br>                }<br>            ] : [{<br>                _id: stockProduct[j]._id,<br>                quantity: stockProduct[j].quantity,<br>                productInfo: tempProduct <br>            }]<br>          } <br><br>           } <br>        } <br>      }<br><br>      responseReturn(res,200,{ <br>        cart_products: p,<br>        price: calculatePrice,<br>        cart_product_count,<br>        shipping_fee: 20 * p.length,<br>        outOfStockProduct,<br>        buy_product_item<br>      })<br>            <br>       } catch (error) {<br>         console.log(error.message)<br>       }<br>       <br>    }<br>    // End Method <br><br><br>    delete_cart_products = async (req, res) =&gt; {<br>        const {cart_id } = req.params<br>        try {<br>            await cartModel.findByIdAndDelete(cart_id)<br>            responseReturn(res,200,{message: &quot;Book is Removed Successfully&quot; })<br>            <br>        } catch (error) {<br>            console.log(error.message)<br>        }<br>         <br>    }<br>       // End Method <br><br>       quantity_inc = async (req, res) =&gt; {<br>        const {cart_id } = req.params<br>        try {<br>            const product = await cartModel.findById(cart_id)<br>            const {quantity} = product<br>            await cartModel.findByIdAndUpdate(cart_id,{quantity: quantity + 1 })<br>            responseReturn(res,200,{message: &quot;Qty Updated&quot; })<br>            <br>        } catch (error) {<br>            console.log(error.message)<br>        }<br>         <br>    }<br>       // End Method <br><br>       quantity_dec = async (req, res) =&gt; {<br>        const {cart_id } = req.params<br>        try {<br>            const product = await cartModel.findById(cart_id)<br>            const {quantity} = product<br>            await cartModel.findByIdAndUpdate(cart_id,{quantity: quantity - 1 })<br>            responseReturn(res,200,{message: &quot;Qty Updated&quot; })<br>            <br>        } catch (error) {<br>            console.log(error.message)<br>        }<br>         <br>    }<br>       // End Method <br><br><br>       add_wishlist = async (req, res) =&gt; {<br>        const { slug } = req.body<br>        try {<br>            const product = await wishlistModel.findOne({slug})<br>                if (product) {<br>                    responseReturn(res, 404 ,{<br>                        error: &#39;Book Is Already In Wishlist&#39;<br>                    })<br>                } else {<br>                    await wishlistModel.create(req.body)<br>                    responseReturn(res, 201 ,{<br>                        message: &#39;Book is Added to the Wishlist Successfully&#39;<br>                    })<br>                }<br>        } catch (error) {<br>            console.log(error.message)<br>        }<br><br>       }<br>       // End Method <br><br><br>       get_wishlist = async (req, res) =&gt; {<br>        const { userId } = req.params<br>        try {<br>            const wishlists = await wishlistModel.find({<br>                userId<br>            })<br>            responseReturn(res, 200, {<br>                wishlistCount: wishlists.length,<br>                wishlists<br>            })<br>            <br>        } catch (error) {<br>            console.log(error.message)<br>        }<br>       } <br>        // End Method <br><br>        remove_wishlist = async (req, res) =&gt; {<br>           const {wishlistId} = req.params<br>           try {<br>            const wishlist = await wishlistModel.findByIdAndDelete(wishlistId) <br>            responseReturn(res, 200,{<br>                message: &#39;Wishlist Book is Removed&#39;,<br>                wishlistId<br>            })<br>            <br>           } catch (error) {<br>            console.log(error.message)<br>           }<br>        }<br> // End Method <br><br>}<br><br>module.exports = new cartController()</pre><p>This cartController manages the core cart and wishlist functionalities for <strong>Book Nation</strong>, a MERN stack e-commerce app. It provides methods to add products to the cart (add_to_cart), retrieve all cart products for a user (get_cart_products), update quantities incrementally (quantity_inc, quantity_dec), and delete items from the cart (delete_cart_products). The controller uses MongoDB aggregation to join cart items with product details, calculates total prices including discounts, handles out-of-stock products, and groups items by sellers to provide shipping fee calculations. In addition to cart features, it supports wishlist operations: adding a book to wishlist (add_wishlist), fetching a user&#39;s wishlist (get_wishlist), and removing items from the wishlist (remove_wishlist). Error handling and responses are standardized using a helper function, ensuring smooth communication between backend and frontend. Overall, this controller forms the backbone of Book Nation’s shopping and wishlist experience, making it easy for users to manage their books efficiently.</p><h3>📦 Cart Page Component in Book Nation</h3><p>The Cart.jsx component represents the <strong>shopping cart page</strong> of the Book Nation e-commerce application. It is built using React and Tailwind CSS and integrates tightly with Redux for state management and routing using React Router.</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import Header from &#39;../components/Header&#39;;<br>import Footer from &#39;../components/Footer&#39;;<br>import { Link, useNavigate } from &#39;react-router-dom&#39;;<br>import { IoIosArrowForward } from &quot;react-icons/io&quot;;<br>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import { get_cart_products, delete_cart_product, messageClear, quantity_inc, quantity_dec } from &#39;../store/reducers/cartReducer&#39;;<br>import toast from &#39;react-hot-toast&#39;;<br><br>const Cart = () =&gt; {<br>    const dispatch = useDispatch();<br>    const { userInfo } = useSelector(state =&gt; state.auth);<br>    const { cart_products, successMessage, price, buy_product_item, shipping_fee, outofstock_products } = useSelector(state =&gt; state.cart);<br>    const navigate = useNavigate();<br><br>    useEffect(() =&gt; {<br>        dispatch(get_cart_products(userInfo.id));<br>    }, []);<br><br>    const redirect = () =&gt; {<br>        navigate(&#39;/shipping&#39;, {<br>            state: {<br>                products: cart_products,<br>                price: price,<br>                shipping_fee: shipping_fee,<br>                items: buy_product_item<br>            }<br>        });<br>    };<br><br>    useEffect(() =&gt; {<br>        if (successMessage) {<br>            toast.success(successMessage);<br>            dispatch(messageClear());<br>            dispatch(get_cart_products(userInfo.id));<br>        }<br>    }, [successMessage]);<br><br>    const inc = (quantity, stock, cart_id) =&gt; {<br>        const temp = quantity + 1;<br>        if (temp &lt;= stock) {<br>            dispatch(quantity_inc(cart_id));<br>        }<br>    };<br><br>    const dec = (quantity, cart_id) =&gt; {<br>        const temp = quantity - 1;<br>        if (temp !== 0) {<br>            dispatch(quantity_dec(cart_id));<br>        }<br>    };<br><br>    return (<br>        &lt;div&gt;<br>            &lt;Header /&gt;<br>            &lt;section className=&#39;bg-[url(https://medium.com/&quot;http://localhost:3000/images/banner/shop.png&quot;)] h-[220px] mt-6 bg-cover bg-no-repeat relative bg-left&#39;&gt;<br>                &lt;div className=&#39;absolute left-0 top-0 w-full h-full bg-[#2422228a]&#39;&gt;<br>                    &lt;div className=&#39;w-[85%] md:w-[80%] sm:w-[90%] lg:w-[90%] h-full mx-auto&#39;&gt;<br>                        &lt;div className=&#39;flex flex-col justify-center gap-1 items-center h-full w-full text-white&#39;&gt;<br>                            &lt;h2 className=&#39;text-3xl font-bold&#39;&gt;Cart Page&lt;/h2&gt;<br>                            &lt;div className=&#39;flex justify-center items-center gap-2 text-2xl w-full&#39;&gt;<br>                                &lt;Link to=&#39;/&#39;&gt;Home&lt;/Link&gt;<br>                                &lt;span className=&#39;pt-1&#39;&gt;&lt;IoIosArrowForward /&gt;&lt;/span&gt;<br>                                &lt;span&gt;Cart&lt;/span&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/section&gt;<br><br>            &lt;section className=&#39;bg-[#eeeeee]&#39;&gt;<br>                &lt;div className=&#39;w-[85%] lg:w-[90%] md:w-[90%] sm:w-[90%] mx-auto py-16&#39;&gt;<br><br>                    {<br>                        cart_products.length &gt; 0 || outofstock_products.length &gt; 0 ? (<br>                            &lt;div className=&#39;flex flex-wrap&#39;&gt;<br>                                &lt;div className=&#39;w-[67%] md-lg:w-full&#39;&gt;<br>                                    &lt;div className=&#39;pr-3 md-lg:pr-0&#39;&gt;<br>                                        &lt;div className=&#39;flex flex-col gap-3&#39;&gt;<br>                                            &lt;div className=&#39;bg-white p-4&#39;&gt;<br>                                                &lt;h2 className=&#39;text-md text-green-500 font-semibold&#39;&gt;Stock Books {cart_products.length}&lt;/h2&gt;<br>                                            &lt;/div&gt;<br><br>                                            {cart_products.map((p, i) =&gt; (<br>                                                &lt;div key={i} className=&#39;flex bg-white p-4 flex-col gap-2&#39;&gt;<br>                                                    &lt;div className=&#39;flex justify-start items-center&#39;&gt;<br>                                                        &lt;h2 className=&#39;text-md text-slate-600 font-bold&#39;&gt;{p.shopName}&lt;/h2&gt;<br>                                                    &lt;/div&gt;<br><br>                                                    {p.products.map((pt, j) =&gt; (<br>                                                        &lt;div key={j} className=&#39;w-full flex flex-wrap&#39;&gt;<br>                                                            &lt;div className=&#39;flex sm:w-full gap-2 w-7/12&#39;&gt;<br>                                                                &lt;div className=&#39;flex gap-2 justify-start items-center&#39;&gt;<br>                                                                    &lt;img className=&#39;w-[80px] h-[80px]&#39; src={pt.productInfo.images[0]} alt=&quot;&quot; /&gt;<br>                                                                    &lt;div className=&#39;pr-4 text-slate-600&#39;&gt;<br>                                                                        &lt;h2 className=&#39;text-md font-semibold&#39;&gt;{pt.productInfo.name}&lt;/h2&gt;<br>                                                                        &lt;span className=&#39;text-sm&#39;&gt;Brand: {pt.productInfo.brand}&lt;/span&gt;<br>                                                                    &lt;/div&gt;<br>                                                                &lt;/div&gt;<br>                                                            &lt;/div&gt;<br><br>                                                            &lt;div className=&#39;flex justify-between w-5/12 sm:w-full sm:mt-3&#39;&gt;<br>                                                                &lt;div className=&#39;pl-4 sm:pl-0&#39;&gt;<br>                                                                    &lt;h2 className=&#39;text-lg text-orange-500&#39;&gt;Rs. {pt.productInfo.price - Math.floor((pt.productInfo.price * pt.productInfo.discount) / 100)}&lt;/h2&gt;<br>                                                                    &lt;p className=&#39;line-through&#39;&gt;Rs. {pt.productInfo.price}&lt;/p&gt;<br>                                                                    &lt;p&gt;-{pt.productInfo.discount}%&lt;/p&gt;<br>                                                                &lt;/div&gt;<br>                                                                &lt;div className=&#39;flex gap-2 flex-col&#39;&gt;<br>                                                                    &lt;div className=&#39;flex bg-slate-200 h-[30px] justify-center items-center text-xl&#39;&gt;<br>                                                                        &lt;div onClick={() =&gt; dec(pt.quantity, pt._id)} className=&#39;px-3 cursor-pointer&#39;&gt;-&lt;/div&gt;<br>                                                                        &lt;div className=&#39;px-3&#39;&gt;{pt.quantity}&lt;/div&gt;<br>                                                                        &lt;div onClick={() =&gt; inc(pt.quantity, pt.productInfo.stock, pt._id)} className=&#39;px-3 cursor-pointer&#39;&gt;+&lt;/div&gt;<br>                                                                    &lt;/div&gt;<br>                                                                    &lt;button onClick={() =&gt; dispatch(delete_cart_product(pt._id))} className=&#39;px-5 py-[3px] bg-red-500 text-white&#39;&gt;Delete&lt;/button&gt;<br>                                                                &lt;/div&gt;<br>                                                            &lt;/div&gt;<br>                                                        &lt;/div&gt;<br>                                                    ))}<br>                                                &lt;/div&gt;<br>                                            ))}<br><br>                                            {outofstock_products.length &gt; 0 &amp;&amp; (<br>                                                &lt;div className=&#39;flex flex-col gap-3&#39;&gt;<br>                                                    &lt;div className=&#39;bg-white p-4&#39;&gt;<br>                                                        &lt;h2 className=&#39;text-md text-red-500 font-semibold&#39;&gt;Out of Stock {outofstock_products.length}&lt;/h2&gt;<br>                                                    &lt;/div&gt;<br><br>                                                    &lt;div className=&#39;bg-white p-4&#39;&gt;<br>                                                        {outofstock_products.map((p, i) =&gt; (<br>                                                            &lt;div key={i} className=&#39;w-full flex flex-wrap&#39;&gt;<br>                                                                &lt;div className=&#39;flex sm:w-full gap-2 w-7/12&#39;&gt;<br>                                                                    &lt;div className=&#39;flex gap-2 justify-start items-center&#39;&gt;<br>                                                                        &lt;img className=&#39;w-[80px] h-[80px]&#39; src={p.products[0].images[0]} alt=&quot;&quot; /&gt;<br>                                                                        &lt;div className=&#39;pr-4 text-slate-600&#39;&gt;<br>                                                                            &lt;h2 className=&#39;text-md font-semibold&#39;&gt;{p.products[0].name}&lt;/h2&gt;<br>                                                                            &lt;span className=&#39;text-sm&#39;&gt;Brand: {p.products[0].brand}&lt;/span&gt;<br>                                                                        &lt;/div&gt;<br>                                                                    &lt;/div&gt;<br>                                                                &lt;/div&gt;<br><br>                                                                &lt;div className=&#39;flex justify-between w-5/12 sm:w-full sm:mt-3&#39;&gt;<br>                                                                    &lt;div className=&#39;pl-4 sm:pl-0&#39;&gt;<br>                                                                        &lt;h2 className=&#39;text-lg text-orange-500&#39;&gt;Rs. {p.products[0].price - Math.floor((p.products[0].price * p.products[0].discount) / 100)}&lt;/h2&gt;<br>                                                                        &lt;p className=&#39;line-through&#39;&gt;Rs. {p.products[0].price}&lt;/p&gt;<br>                                                                        &lt;p&gt;-{p.products[0].discount}%&lt;/p&gt;<br>                                                                    &lt;/div&gt;<br>                                                                    &lt;div className=&#39;flex gap-2 flex-col&#39;&gt;<br>                                                                        &lt;div className=&#39;flex bg-slate-200 h-[30px] justify-center items-center text-xl&#39;&gt;<br>                                                                            &lt;div onClick={() =&gt; dec(p.quantity, p._id)} className=&#39;px-3 cursor-pointer&#39;&gt;-&lt;/div&gt;<br>                                                                            &lt;div className=&#39;px-3&#39;&gt;{p.quantity}&lt;/div&gt;<br>                                                                            &lt;div className=&#39;px-3 cursor-pointer&#39;&gt;+&lt;/div&gt;<br>                                                                        &lt;/div&gt;<br>                                                                        &lt;button onClick={() =&gt; dispatch(delete_cart_product(p._id))} className=&#39;px-5 py-[3px] bg-red-500 text-white&#39;&gt;Delete&lt;/button&gt;<br>                                                                    &lt;/div&gt;<br>                                                                &lt;/div&gt;<br>                                                            &lt;/div&gt;<br>                                                        ))}<br>                                                    &lt;/div&gt;<br>                                                &lt;/div&gt;<br>                                            )}<br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br><br>                                &lt;div className=&#39;w-[33%] md-lg:w-full&#39;&gt;<br>                                    &lt;div className=&#39;pl-3 md-lg:pl-0 md-lg:mt-5&#39;&gt;<br>                                        {cart_products.length &gt; 0 &amp;&amp; (<br>                                            &lt;div className=&#39;bg-white p-3 text-slate-600 flex flex-col gap-3&#39;&gt;<br>                                                &lt;h2 className=&#39;text-xl font-bold&#39;&gt;Order Summary&lt;/h2&gt;<br>                                                &lt;div className=&#39;flex justify-between items-center&#39;&gt;<br>                                                    &lt;span&gt;{buy_product_item} Items&lt;/span&gt;<br>                                                    &lt;span&gt;Rs. {price}&lt;/span&gt;<br>                                                &lt;/div&gt;<br>                                                &lt;div className=&#39;flex justify-between items-center&#39;&gt;<br>                                                    &lt;span&gt;Shipping Fee&lt;/span&gt;<br>                                                    &lt;span&gt;Rs. {shipping_fee}&lt;/span&gt;<br>                                                &lt;/div&gt;<br>                                                &lt;div className=&#39;flex gap-2&#39;&gt;<br>                                                    &lt;input className=&#39;w-full px-3 py-2 border border-slate-200 outline-0 focus:border-green-500 rounded-sm&#39; type=&quot;text&quot; placeholder=&#39;Input Voucher Coupon&#39; /&gt;<br>                                                    &lt;button className=&#39;px-5 py-[1px] bg-[#059473] text-white rounded-sm uppercase text-sm&#39;&gt;Apply&lt;/button&gt;<br>                                                &lt;/div&gt;<br>                                                &lt;div className=&#39;flex justify-between items-center&#39;&gt;<br>                                                    &lt;span&gt;Total&lt;/span&gt;<br>                                                    &lt;span className=&#39;text-lg text-[#059473]&#39;&gt;Rs. {price + shipping_fee}&lt;/span&gt;<br>                                                &lt;/div&gt;<br>                                                &lt;button onClick={redirect} className=&#39;px-5 py-[6px] rounded-sm hover:shadow-red-500/50 hover:shadow-lg bg-red-500 text-sm text-white uppercase &#39;&gt;<br>                                                    Process to Checkout ({buy_product_item})<br>                                                &lt;/button&gt;<br>                                            &lt;/div&gt;<br>                                        )}<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                        ) : (<br>                            &lt;div&gt;<br>                                &lt;Link className=&#39;px-4 py-1 bg-indigo-500 text-white&#39; to=&#39;/shops&#39;&gt;Shop Now&lt;/Link&gt;<br>                            &lt;/div&gt;<br>                        )<br>                    }<br>                &lt;/div&gt;<br>            &lt;/section&gt;<br><br>            &lt;Footer /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default Cart;</pre><h4>🔁 Data Fetching &amp; State Management</h4><p>The component:</p><ul><li>Uses useSelector to extract data like cart_products, userInfo, total price, number of items (buy_product_item), shipping_fee, and outofstock_products from Redux state.</li><li>Uses useEffect to <strong>fetch the user’s cart products</strong> when the component mounts via dispatch(get_cart_products(userInfo.id)).</li><li>Listens for any successMessage (e.g., after item deletion or quantity update), shows it using react-hot-toast, and refreshes the cart.</li></ul><h4>➕➖ Quantity Controls</h4><p>Each product’s quantity can be increased or decreased:</p><ul><li>inc(quantity, stock, cart_id): Increases the quantity if it’s less than the product&#39;s stock.</li><li>dec(quantity, cart_id): Decreases the quantity if it’s greater than 1.<br> Both dispatch the corresponding Redux actions (quantity_inc, quantity_dec).</li></ul><h4>❌ Item Removal</h4><p>Users can remove products from their cart or from the out-of-stock list by clicking the <strong>Delete</strong> button. This dispatches delete_cart_product.</p><h4>🧾 Order Summary</h4><p>The right-hand sidebar displays:</p><ul><li>Total number of items and price.</li><li>Shipping fee.</li><li>Input field for a voucher code (though functionality isn’t implemented yet).</li><li>A <strong>Total</strong> amount (price + shipping_fee).</li><li>A <strong>“Process to Checkout”</strong> button that redirects to the /shipping page with all required data passed through navigate().</li></ul><h4>🚫 Out-of-Stock Handling</h4><p>Out-of-stock products are displayed in a separate section. Quantity buttons are present but non-functional (no increment dispatch), indicating they’re inactive. These can still be removed from the cart.</p><h4>🖼️ UI/UX</h4><ul><li>A header image banner is shown at the top for branding.</li><li>Products are grouped by the seller’s shopName.</li><li>Responsive design: It adapts well to smaller screen sizes using Tailwind’s utility classes.</li><li>Empty cart fallback: If no products are available, it shows a “Shop Now” link.</li></ul><h4>🔄 Routing &amp; Navigation</h4><ul><li>Navigation is handled using useNavigate from react-router-dom.</li><li>Breadcrumb navigation (Home &gt; Cart) is also included for better user experience.</li></ul><p>📆 What’s Next?</p><p>Here’s a glimpse of what’s lined up for Week 6:</p><p>🔹 Adding Rating for the books</p><p>GitHub Repo</p><p>Frontend — <a href="https://github.com/yathu1/multi-vendor-books-front-end">https://github.com/yathu1/multi-vendor-books-front-end</a> Backend — <a href="https://github.com/yathu1/multivendor-backend">https://github.com/yathu1/multivendor-backend</a><br>Dashboard — <a href="https://github.com/yathu1/multivendor-books-dashboard">https://github.com/yathu1/multivendor-books-dashboard</a></p><p>Thanks for reading — stay tuned for the Week 7update!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea41b0b8b00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>