<?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 Darren Marcello on Medium]]></title>
        <description><![CDATA[Stories by Darren Marcello on Medium]]></description>
        <link>https://medium.com/@darren.marcello?source=rss-969619602662------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9CcHaNY0NCmjIwOT</url>
            <title>Stories by Darren Marcello on Medium</title>
            <link>https://medium.com/@darren.marcello?source=rss-969619602662------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:56:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darren.marcello/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[Monitoring Admin Features in PantauTular with Sentry and Structured Logging]]></title>
            <link>https://medium.com/@darren.marcello/monitoring-admin-features-in-pantautular-with-sentry-and-structured-logging-418df6b354b8?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/418df6b354b8</guid>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 10:23:50 GMT</pubDate>
            <atom:updated>2025-12-01T12:15:57.910Z</atom:updated>
            <content:encoded><![CDATA[<p>The admin area in PantauTular is used to manage user roles and see user activity.<br> This area is very sensitive because:</p><ul><li>It changes who has access to curator and expert features</li><li>Only admin users should call these endpoints</li><li>If something is slow or broken, it can block many users</li></ul><p>After my friend added full monitoring for the curator backend, I implemented a similar pattern for the <strong>admin feature</strong>.<br> I used:</p><ul><li><strong>Sentry</strong> for errors, events, and traces</li><li><strong>Structured JSON logging</strong> for clear context</li><li>A shared mixin called AdminMonitoringMixin in Django views</li></ul><p>This blog explains how the monitoring works from the admin page in the frontend to Sentry in the backend.</p><h3>1. From Admin UI to Sentry</h3><p>When an admin opens the <strong>User Role Management</strong> page and changes a user role, this is what happens:</p><ol><li>The frontend (Next.js) calls<br> PUT /admin-feature/users/{id}/role</li><li>The backend (Django) runs the logic and records:</li></ol><ul><li>How long the request took</li><li>Whether it succeeded or failed</li><li>Which admin did it and which user was the target</li></ul><p>3. The backend sends structured logs that are captured by Sentry as events such as:</p><ul><li>admin.users.change_role.duration</li><li>admin.users.change_role.success</li><li>admin.users.change_role.not_found or .error if something goes wrong</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy23sfWdbp9yevI5nbl8Sw.png" /><figcaption><strong><em>Image 0</em></strong><em> — User Role Management page in PantauTular with a success toast like “Peran berhasil disimpan”</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q5LfylP9-NmmFK24cxf5g.png" /><figcaption>on backend terminal</figcaption></figure><h3>2. Sentry Setup and Monitoring Logger in settings.py</h3><p>At project level I configure Sentry with Django integration and logging integration. For the admin feature I also add flags and a dedicated logger pantautular.monitoring.</p><pre># settings.py<br><br>SENTRY_DSN = os.getenv(&quot;SENTRY_DSN&quot;, &quot;&quot;)<br>SENTRY_ENVIRONMENT = os.getenv(&quot;SENTRY_ENVIRONMENT&quot;, &quot;local&quot;)<br><br>sentry_sdk.init(<br>    dsn=SENTRY_DSN,<br>    integrations=[<br>        DjangoIntegration(),<br>        LoggingIntegration(<br>            level=logging.INFO,          # all INFO+ logs go through the SDK<br>            event_level=logging.WARNING  # WARNING+ becomes Sentry events<br>        ),<br>    ],<br>    traces_sample_rate=1.0,<br>    profiles_sample_rate=1.0,<br>    environment=SENTRY_ENVIRONMENT,<br>    send_default_pii=True,<br>)<br><br># Feature flags for admin monitoring<br>ADMIN_MONITORING_SEND_TO_SENTRY = True<br>ADMIN_MONITORING_SEND_SUCCESS_TO_SENTRY = True<br>ADMIN_FEATURE_SLOW_THRESHOLD_MS = 1200</pre><p>Then I define logging for structured JSON:</p><pre>LOGGING = {<br>    &quot;version&quot;: 1,<br>    &quot;disable_existing_loggers&quot;: False,<br>    &quot;formatters&quot;: {<br>        &quot;json&quot;: {<br>            &quot;()&quot;: &quot;pantau_tular.logging_utils.StructuredJsonFormatter&quot;,<br>        },<br>    },<br>    &quot;handlers&quot;: {<br>        &quot;console&quot;: {<br>            &quot;class&quot;: &quot;logging.StreamHandler&quot;,<br>            &quot;formatter&quot;: &quot;json&quot;,<br>        },<br>    },<br>    &quot;loggers&quot;: {<br>        &quot;pantautular.monitoring&quot;: {<br>            &quot;handlers&quot;: [&quot;console&quot;],<br>            &quot;level&quot;: &quot;INFO&quot;,<br>            &quot;propagate&quot;: False,<br>        },<br>    },<br>}</pre><p>The StructuredJsonFormatter adds standard fields like timestamp, level, and logger to every log record. This makes the log easy to filter in Sentry or other tools.</p><h3>3. AdminMonitoringMixin: One Mixin for All Admin Endpoints</h3><p>To avoid copy paste and to keep all admin endpoints consistent, I created AdminMonitoringMixin.<br> This mixin:</p><ul><li>Builds a default context (user id, endpoint name, extra fields)</li><li>Measures request duration with record_duration</li><li>Sends events with log_event</li></ul><pre>class AdminMonitoringMixin:<br>    &quot;&quot;&quot;Helper to emit monitoring events and durations for admin feature.&quot;&quot;&quot;<br><br>    monitoring_default_threshold_ms = DEFAULT_ADMIN_FEATURE_SLOW_THRESHOLD_MS<br><br>    def _monitor_context(self, request, **extra):<br>        user = getattr(request, &quot;user&quot;, None)<br>        context = {<br>            &quot;user_id&quot;: getattr(user, &quot;id&quot;, None),<br>            &quot;endpoint&quot;: getattr(self, &quot;monitoring_endpoint&quot;, self.__class__.__name__),<br>        }<br>        for key, value in extra.items():<br>            if value is not None:<br>                context[key] = value<br>        return context<br><br>    def monitor_duration(self, event: str, request, warn_message: str = None, **extra):<br>        threshold_ms = getattr(<br>            settings,<br>            &quot;ADMIN_FEATURE_SLOW_THRESHOLD_MS&quot;,<br>            self.monitoring_default_threshold_ms,<br>        )<br>        return record_duration(<br>            event,<br>            threshold_ms=threshold_ms,<br>            warn_message=warn_message,<br>            **self._monitor_context(request, **extra),<br>        )<br><br>    def monitor_event(self, event: str, request, **extra):<br>        context = self._monitor_context(request, **extra)<br>        log_event(event, **context)</pre><p>With this mixin, each view only needs to:</p><ul><li>Set monitoring_endpoint = &quot;admin.users.change_role&quot; (for example)</li><li>Wrap core logic in with self.monitor_duration(...):</li><li>Call self.monitor_event(..., status=&quot;success&quot;) after success</li></ul><h3>4. Example: Changing a User Role</h3><p>The most critical admin endpoint is the one that changes a user role.<br> Here is a simplified version of AdminUserChangeRoleView:</p><pre>class AdminUserChangeRoleView(AuditLogMixin, AdminMonitoringMixin, APIView):<br>    authentication_classes = [CustomJWTAuthentication]<br>    permission_classes = [IsTokenAuthenticated, IsAdminRole]<br>    monitoring_endpoint = &quot;admin.users.change_role&quot;<br><br>    @transaction.atomic<br>    def put(self, request, id):<br>        event = self.monitoring_endpoint<br><br>        # 1) Target user not found<br>        try:<br>            user = User.objects.get(id=id)<br>        except User.DoesNotExist:<br>            self.monitor_event(<br>                f&quot;{event}.not_found&quot;,<br>                request,<br>                status=&quot;not_found&quot;,<br>                target_user_id=id,<br>            )<br>            self.sentry_message(&quot;admin.users.change_role.not_found&quot;, level=&quot;warning&quot;)<br>            return Response(<br>                {&quot;detail&quot;: &quot;User not found&quot;},<br>                status=status.HTTP_404_NOT_FOUND,<br>            )<br><br>        # 2) Measure duration of the role change process<br>        with self.monitor_duration(event, request, target_user_id=user.id):<br>            serializer = RoleAssignmentSerializer(data=request.data)<br>            serializer.is_valid(raise_exception=True)<br>            role_obj = serializer.validated_data[&quot;role&quot;]<br>            previous_role = user.role_name<br><br>            # business logic to update the role<br>            # ...<br><br>            self.log(<br>                request=request,<br>                action=&quot;CHANGE_ROLE&quot;,<br>                detail=f&quot;Changed role for user_id={user.id} to &#39;{role_obj.name}&#39;&quot;,<br>                note=f&quot;path={request.path} method={request.method}&quot;,<br>            )<br><br>        # 3) Emit success event<br>        self.monitor_event(<br>            f&quot;{event}.success&quot;,<br>            request,<br>            status=&quot;success&quot;,<br>            target_user_id=user.id,<br>            new_role=role_obj.name,<br>            previous_role=previous_role,<br>        )<br>        return Response(UserSerializer(user).data, status=status.HTTP_200_OK)</pre><h3>What Sentry Shows</h3><p>When I log in as admin, open the role management page, and change a role, Sentry creates an issue like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKe-7eRg01e1cy-OvRgOXA.png" /><figcaption><a href="https://pantautular.sentry.io/issues/7059377770/?query=is%3Aunresolved&amp;referrer=issue-stream">https://pantautular.sentry.io/issues/7059377770/?query=is%3Aunresolved&amp;referrer=issue-stream</a></figcaption></figure><p>If I open one event and look at the JSON or Context tab, I can see fields such as:</p><ul><li>event: &quot;admin.users.change_role.success&quot;</li><li>user_id (admin id)</li><li>target_user_id</li><li>previous_role and new_role</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PgaKTIw2uU2etvQm8oBuw.png" /><figcaption><strong>Image 2</strong> — JSON context for <em>admin.users.change_role.success</em> that shows these fields.</figcaption></figure><p>The same information also appears in the console as structured JSON:</p><pre>{<br>  &quot;event_id&quot;: &quot;e0e91fed1234567890abcdef12345678&quot;,<br>  &quot;level&quot;: &quot;info&quot;,<br>  &quot;logger&quot;: &quot;pantautular.monitoring&quot;,<br>  &quot;logentry&quot;: {<br>    &quot;formatted&quot;: &quot;admin.users.change_role.success | ctx={&#39;user_id&#39;: 7, &#39;endpoint&#39;: &#39;admin.users.change_role&#39;, &#39;status&#39;: &#39;success&#39;, &#39;target_user_id&#39;: 3, &#39;previous_role&#39;: &#39;CURATOR&#39;, &#39;new_role&#39;: &#39;CONTRIBUTOR&#39;}&quot;<br>  },<br>  &quot;extra&quot;: {<br>    &quot;event&quot;: &quot;admin.users.change_role.success&quot;,<br>    &quot;endpoint&quot;: &quot;admin.users.change_role&quot;,<br>    &quot;user_id&quot;: 7,<br>    &quot;target_user_id&quot;: 3,<br>    &quot;previous_role&quot;: &quot;CURATOR&quot;,<br>    &quot;new_role&quot;: &quot;CONTRIBUTOR&quot;,<br>    &quot;status&quot;: &quot;success&quot;<br>  }<br>}</pre><p>From a single role change flow I can answer:</p><ul><li>Who changed the role</li><li>Which user was changed</li><li>What the previous and new roles were</li><li>How long the operation took</li></ul><h3>5. Other Admin Endpoints Using the Same Pattern</h3><p>AdminMonitoringMixin is reused in other admin views as well.</p><p>Examples:</p><ul><li>AdminUserListView</li><li>monitoring_endpoint = &quot;admin.users.list&quot;</li><li>Emits admin.users.list.duration and admin.users.list.success (with user count)</li><li>AdminUserDeleteView</li><li>Emits admin.users.delete.success</li><li>Also .not_found or .forbidden when needed</li><li>AdminUserLogsAllAPIView</li><li>monitoring_endpoint = &quot;admin.user_logs.all&quot;</li><li>Emits admin.user_logs.all.duration and admin.user_logs.all.success with total log entries</li><li>AdminUserInfoView</li><li>Emits admin.user.info.success whenever the admin profile info is loaded</li></ul><p>In Sentry, if I filter the issues list with admin.users or logger:pantautular.monitoring, I see a group of issues from these endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMriIdJc8dimyenlOJ3YWw.png" /><figcaption><strong><em>Image 3</em></strong><em> — Sentry Issues list filtered by admin monitoring events.</em></figcaption></figure><p>This shows that monitoring is not only for one endpoint, but for the whole admin feature.</p><h3>6. Context, Breadcrumbs, and Traces</h3><p>Besides the JSON payload, Sentry also stores:</p><ul><li><strong>Breadcrumbs</strong> — small events and logs before the main event</li><li><strong>Trace</strong> — the flow of the request through the stack</li><li><strong>Tags and Context</strong> — environment, release id, OS, browser, and more</li></ul><p>For one admin event, for example admin.users.change_role.success, the event detail screen shows:</p><ul><li>HTTP method and URL</li><li>Status code</li><li>Timeline of the request</li><li>Which release and environment it uses</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*A5ca3Ob9o3dVDrO-LzH6Cw.png" /></figure><p>This helps when I need to debug slow requests or environment specific issues.</p><h3>7. Frontend Connection: User Role Management Page</h3><p>In the frontend, the Role Management page is built with Next.js and Tailwind.<br> When the admin changes a role, the page:</p><ol><li>Sends a PUT request to /admin-feature/users/{id}/role</li><li>Shows a green success toast</li><li>Rolls back the UI if something fails</li></ol><p>Simplified code:</p><pre>const onSaveRole = async (user: User, newRole: Role) =&gt; {<br>  const prev = users;<br>  setUsers(p =&gt;<br>    p.map(u =&gt; u.id === user.id ? { ...u, role: newRole } : u)<br>  );<br>try {<br>    const res = await fetch(`${API_BASE}/admin-feature/users/${user.id}/role`, {<br>      method: &quot;PUT&quot;,<br>      headers: authHeaders(),<br>      credentials: &quot;include&quot;,<br>      body: JSON.stringify({ role_name: newRole }),<br>    });<br>    if (!res.ok) {<br>      setUsers(prev);<br>      throw new Error(&quot;Failed to update role&quot;);<br>    }<br>    pushToast({ type: &quot;success&quot;, id: &quot;role-saved&quot;, title: &quot;Peran berhasil disimpan&quot; });<br>  } catch {<br>    setUsers(prev);<br>    pushToast({ type: &quot;error&quot;, id: &quot;role-error&quot;, title: &quot;Gagal menyimpan perubahan peran&quot; });<br>  }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy23sfWdbp9yevI5nbl8Sw.png" /></figure><p>For every success toast in the UI there is a matching event admin.users.change_role.success in Sentry. This connects the user experience on the frontend with observability on the backend.</p><h3>8. What Is Monitored in the Admin Feature</h3><p>Here is a quick summary of what I monitor.</p><h4>Events and Logs</h4><ul><li>admin.users.list.duration, admin.users.list.success</li><li>admin.users.change_role.duration, .success, .not_found</li><li>admin.users.delete.success, .not_found, .forbidden</li><li>admin.user_logs.all.duration, .success</li><li>admin.user.info.success</li></ul><p>Each event carries context fields such as:</p><ul><li>user_id (admin who triggers the action)</li><li>target_user_id (for per user actions)</li><li>endpoint</li><li>previous_role and new_role (for role changes)</li><li>duration_ms (for performance)</li></ul><h4>Benefits</h4><p>This monitoring gives several benefits:</p><ol><li><strong>Clear audit trail</strong><br> Every admin action that changes roles or deletes users is recorded with who, what, and when.</li><li><strong>Endpoint level performance insight</strong><br> I can see which admin endpoints are slow, not just that “the server is slow”.</li><li><strong>Reuse of existing observability stack</strong><br> The admin feature uses the same structured logging and Sentry setup as the curator feature, so maintenance is simpler.</li><li><strong>Matches platform monitoring learning goals</strong><br> The setup uses standard tools, custom configuration for specific components, and shows more advanced usage such as business events and context for each request.</li></ol><h3>Final Takeaway</h3><p>By adding AdminMonitoringMixin, structured JSON logs, and Sentry integration to the admin feature, PantauTular now has better visibility into all important admin actions.</p><ul><li>Admins get a smooth UI with clear success and error messages.</li><li>Developers and operators get detailed monitoring for performance and security sensitive operations.</li></ul><p>This monitoring setup makes the admin feature safer to use, easier to debug, and more ready to scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=418df6b354b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Working Code to Lasting Code: Refactoring Frontend PantauTular]]></title>
            <link>https://medium.com/@darren.marcello/from-working-code-to-lasting-code-refactoring-frontend-pantautular-fde88611ae81?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde88611ae81</guid>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 10:18:34 GMT</pubDate>
            <atom:updated>2025-11-26T15:54:26.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*Xtw0HKX4BDLbaJt4.jpeg" /></figure><h3>1. Refactoring &amp; Design Pattern</h3><h4>1.1 Refactoring ala Martin Fowler</h4><p>Refactoring, from Martin Fowler, is a proccess changing internal structure code without changing its function. Example in the frontend, that mean UI still works the same in user view, but in the other side:</p><ul><li>The function is dispart(dipisah) to several small and clear part, Rename variable, Reduce duplication code, and More organize file structure.</li></ul><p>the purpose is not only for looks good, but it for:</p><ul><li>make the code more readable, easy to test, and more secure when new requirement come like new role, new filter, new table column.</li></ul><h4>1.2 Best Practice di Framework / Bahasa yang Digunakan</h4><p>A <strong>best practice</strong> is a way of writing code that is widely considered “good style” in a language or framework.<br>For example in on my frontend using React/Next.js:</p><ul><li>Keep components small and focused.</li><li>Put API calls in a separate file or custom hook, not directly inside every component.</li><li>Use clear naming and TypeScript types for props and data.</li></ul><p>Function: Best practices make your code more consistent and easier for teams to work with. They are not strict rules, but strong guidelines.</p><h4><strong>1.3 Design pattern dalam skala enterprise</strong></h4><p>A <strong>design pattern</strong> is a reusable way to solve a common problem in code. It’s not a library or a framework, but more like a “template” or “recipe” for how to structure your code.<br>Example idea (not code-specific):</p><ul><li>You have UI, business logic, and data access. A common pattern is to <strong>separate</strong> them into different layers so they don’t depend on each other too tightly.</li></ul><p>Function: Design patterns help your code stay organized, easier to change, and easier to understand by other developers.</p><h4><strong>1.4 Pola umum: DTO, service layer, repository layer</strong></h4><p>A <strong><em>DTO (Data Transfer Object)</em> </strong>is a simple object used to send data between layers (for example, between backend and frontend, or between service and controller). It usually only has fields, no business logic.<br>Function:</p><ul><li>Control what data goes in and out (avoid exposing internal model directly).</li><li>Make the API contract clear and stable.</li><li>Sometimes adapt/rename fields to what the client actually needs.</li></ul><p>A <strong><em>service layer</em></strong> is where you put <strong>business logic</strong>: rules, calculations, and workflows. The service layer is used by controllers (backend) or pages/components (frontend).<br>Function:</p><ul><li>Keep controllers/pages thin: they just call service methods.</li><li>Avoid duplicating logic across multiple endpoints or screens.</li><li>Make it easier to test logic without worrying about HTTP or UI.</li></ul><p>A<em> </em><strong><em>repository layer</em></strong> is an abstraction for data access. On the backend, it talks to the database. On the frontend, it can be a central module that talks to APIs.<br>Function:</p><ul><li>Centralize all “how to fetch/save data”.</li><li>Make it easier to change the data source later (e.g., change endpoint or DB) without touching business logic.</li><li>Make tests easier (you can mock the repository).</li></ul><h3>2. Project and Frontend Page Overview</h3><p>PantauTular is a web application for monitoring disease cases, built with a React + Next.js frontend and a separate backend API. On the frontend, each page not only shows data, but also has to handle roles, validation, and user flows such as uploading cases or editing reports.</p><p>In this blog, I focus on the <strong>Curator Add Data</strong> page. This page allows users with roles like ADMIN, CURATOR, or EXP_USER to upload case data and apply filters. The page needs to do several things at once: check user access, show a consistent layout with the shared Navbar and Footer components, validate form input such as disease type, location, date, and age, and coordinate the CsvUpload component so that uploaded data is processed safely. Because of that, the internal structure of this page is a good place to talk about refactoring and design patterns on the frontend.</p><h3>3. Current Frontend Structure of the Curator Add Data Page</h3><p>The Curator Add Data page already shows some separation of responsibilities, even before adding more advanced patterns. At the top of the file, the page imports shared UI components like Navbar, Footer, and AccessDeniedNotice, plus the CsvUpload component and the useAuth hook. This means the layout, the access check, and the upload UI are not hard-coded inside one giant JSX tree; they are delegated to reusable pieces.</p><p>The file also defines clear TypeScript types such as FilterState, FilterStateDashboard, and User. These types act like simple DTOs on the frontend: they describe the shape of data that flows through the page, rather than letting everything be any or raw JSON. When the page keeps its state in a FilterState or passes a User object around, it becomes harder to accidentally pass the wrong fields or forget required values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*rSimS4DoE2bxDLo9CaVoOw.png" /></figure><p>One important refactoring that is already visible is the validateFormState function. It is exported as a pure function that receives a small input object with fields like jenisPenyakit, lokasi, tanggal, sumberBerita, and usia, and then returns a map of validation errors. Inside the page component, this function can be called whenever the user submits or changes the form, but the function itself does not depend on React state or the browser. This makes the validation logic easier to test and easier to reuse. It also matches the idea of a small “service” on the frontend: a function dedicated to business rules (for example, “date must be valid” or “age must be a non-negative integer string”), not to rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*F6QrFbqzcDYj7g5A3p2HMg.png" /></figure><p>The main React component, CuratorAddDataPage, then focuses on wiring these pieces together. It uses useAuth() to get the current user and decide whether to show the content or an access denied notice. It keeps track of filterState and effectiveUser with useState, and it coordinates navigation using useRouter. Instead of mixing string parsing, date checks, and UI layout in one block, the component calls validateFormState for validation, and hands off upload behavior to CsvUpload.</p><p>In simple terms, the page is already moving toward an enterprise-style structure, but on the frontend: there is a clear layout layer (shared components), a bit of a service layer (pure validation function and upload component), and typed data structures that behave like DTOs. In the next part of the blog, I will describe how I see these patterns as a form of refactoring, and what I would still improve to make the code even more modular and easier to change.</p><h3>4. Cleaning Up for Humans: Refactoring for Readability</h3><p>Originally, the Curator Add Data page tried to do many things inside a single component:</p><ul><li>Check the authenticated user and their role</li><li>Manage all form fields and validation inline</li><li>Render layout, titles, and upload UI in one JSX block</li></ul><p>This led to:</p><ul><li>A page component that was hard to scan</li><li>Validation rules mixed with UI code</li><li>More mental load when adding or changing fields</li></ul><p><strong>Before (simplified example — everything inside one component):</strong></p><pre>// Before: mixed layout, auth, and validation in one place<br>export default function CuratorAddDataPage() {<br>  const { user } = useAuth();<br>  const [form, setForm] = useState({ disease: &quot;&quot;, location: &quot;&quot;, age: &quot;&quot; });<br>  const [errors, setErrors] = useState&lt;{ [k: string]: string }&gt;({});<br>if (!user) {<br>    return &lt;div&gt;You are not allowed to access this page.&lt;/div&gt;;<br>  }<br>  const onSubmit = () =&gt; {<br>    const next: any = {};<br>    if (!form.disease) next.disease = &quot;Required&quot;;<br>    if (!form.location) next.location = &quot;Required&quot;;<br>    if (form.age &amp;&amp; !/^\d+$/.test(form.age)) next.age = &quot;Must be a number&quot;;<br>    setErrors(next);<br>    if (Object.keys(next).length === 0) {<br>      // call upload logic directly here<br>    }<br>  };<br>  return (<br>    &lt;div&gt;<br>      {/* navbar, form, and footer all inline here */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>After (using shared layout + separate validator + CsvUpload):</strong></p><pre>// After: clearer separation of concerns<br>import Navbar from &quot;../components/Navbar&quot;;<br>import Footer from &quot;../components/Footer&quot;;<br>import AccessDeniedNotice from &quot;../components/AccessDenied&quot;;<br>import CsvUpload from &quot;../components/CsvUpload&quot;;<br>import { useAuth } from &quot;../auth/hooks/useAuth&quot;;<br>export function validateFormState(input: {<br>  jenisPenyakit?: string;<br>  lokasi?: string;<br>  tanggal?: { dd?: string; mm?: string; yyyy?: string };<br>  sumberBerita?: string;<br>  usia?: string;<br>}) {<br>  const { jenisPenyakit = &quot;&quot;, lokasi = &quot;&quot;, tanggal = {}, sumberBerita = &quot;&quot;, usia = &quot;&quot; } = input;<br>  const next: Record&lt;string, string&gt; = {};<br>  if (!jenisPenyakit) next.jenisPenyakit = &quot;Jenis penyakit wajib diisi&quot;;<br>  if (!lokasi) next.lokasi = &quot;Lokasi wajib diisi&quot;;<br>  const hasDate = tanggal.dd || tanggal.mm || tanggal.yyyy;<br>  if (!hasDate) next.tanggal = &quot;Tanggal wajib diisi&quot;;<br>  else if (!tanggal.dd || !tanggal.mm || !tanggal.yyyy) next.tanggal = &quot;Format tanggal belum lengkap&quot;;<br>  if (!sumberBerita) next.sumberBerita = &quot;Sumber berita wajib diisi&quot;;<br>  if (usia &amp;&amp; !/^\d+$/.test(usia)) next.usia = &quot;Usia harus berupa angka&quot;;<br>  return next;<br>}<br>export default function CuratorAddDataPage() {<br>  const { user } = useAuth();<br>  if (!user) {<br>    return (<br>      &lt;&gt;<br>        &lt;Navbar /&gt;<br>        &lt;AccessDeniedNotice /&gt;<br>        &lt;Footer /&gt;<br>      &lt;/&gt;<br>    );<br>  }<br>  return (<br>    &lt;&gt;<br>      &lt;Navbar /&gt;<br>      &lt;main className=&quot;px-6 py-4&quot;&gt;<br>        &lt;h1 className=&quot;text-xl font-semibold mb-4&quot;&gt;Curator – Add Data&lt;/h1&gt;<br>        &lt;CsvUpload currentUser={user} /&gt;<br>      &lt;/main&gt;<br>      &lt;Footer /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>Reflection:</strong><br> The feature still behaves the same, but the page component now reads like a short story: check auth → show layout → render upload. Validation lives in a dedicated function, which makes the file easier to read and maintain.</p><h3>5. Beyond React Defaults, Applying Patterns on the Frontend</h3><p>React and Next.js only give basic building blocks: components, hooks, and routing. In this project, I applied some patterns that go beyond the default:</p><ul><li>A dedicated useAuth hook to encapsulate authentication logic</li><li>A centralized services/api module used by pages instead of calling fetch directly</li></ul><p>This turns the frontend into a layered structure: the page becomes a thin UI layer, while hooks and services act like a service/repository layer on the client side.</p><p><strong>Example: using </strong><strong>useAuth as an auth service, not inline logic</strong></p><pre>// useAuth hook (conceptually)<br>export function useAuth() {<br>  const [user, setUser] = useState&lt;User | null&gt;(null);<br>  const [loading, setLoading] = useState(true);<br>useEffect(() =&gt; {<br>    // read token, fetch current user, etc.<br>    // then setUser(...)<br>    setLoading(false);<br>  }, []);<br>  return { user, loading, isAuthenticated: !!user };<br>}</pre><p><strong>Example: using a service module instead of inline fetch</strong></p><pre>// services/api.ts<br>export const registryApi = {<br>  async getDiseases() {<br>    const res = await fetch(&quot;/api/diseases&quot;);<br>    if (!res.ok) throw new Error(&quot;Failed to load diseases&quot;);<br>    return res.json();<br>  },<br>};</pre><pre>// curator-edit-delete-data/page.tsx (using the service)<br>useEffect(() =&gt; {<br>  let mounted = true;<br>async function loadDiseases() {<br>    try {<br>      // allow injected services in tests<br>      // eslint-disable-next-line @typescript-eslint/ban-ts-comment<br>      // @ts-ignore<br>      const injected =<br>        typeof global !== &quot;undefined&quot; ? (global as any).__TEST_INJECT_SERVICES__ : undefined;<br>      const svc = injected ?? (await import(&quot;../../services/api&quot;));<br>      if (!mounted) return;<br>      if (svc.registryApi &amp;&amp; typeof svc.registryApi.getDiseases === &quot;function&quot;) {<br>        const remoteDiseases = await svc.registryApi.getDiseases();<br>        // use diseases in state here<br>      }<br>    } catch {<br>      // handle error<br>    }<br>  }<br>  loadDiseases();<br>  return () =&gt; {<br>    mounted = false;<br>  };<br>}, []);</pre><p><strong>Reflection:</strong><br> These patterns are not required by React, but they help the frontend look more like an organized application: pages ask for data from a service, instead of mixing UI code with network details.</p><h3>6. Using Patterns Consistently — Benefits and Trade-offs</h3><p>Once these patterns are in place, they appear in multiple parts of the frontend:</p><ul><li>Shared layout components: Navbar, Footer, AccessDeniedNotice</li><li>Shared auth hook: useAuth for any page that needs user information</li><li>Shared service module: services/api for registry-related data</li></ul><p>This consistency brings clear benefits:</p><ul><li>Layout changes (logo, navigation) can be done in one component and reflected everywhere</li><li>Any page can check auth in the same way by calling useAuth()</li><li>API behavior can be updated in services/api without touching UI components</li></ul><p>However, there are trade-offs:</p><ul><li>The number of files and layers increases</li><li>New developers must first understand the structure (components → hooks → services)</li><li>For very simple pages, this pattern can feel heavier than necessary</li></ul><p><strong>Example: same layout/auth pattern reused across pages</strong></p><pre>// admin-role-management/page.tsx<br>import Navbar from &quot;../components/Navbar&quot;;<br>import Footer from &quot;../components/Footer&quot;;<br>import AccessDeniedNotice from &quot;../components/AccessDenied&quot;;<br>import { useAuth } from &quot;../auth/hooks/useAuth&quot;;<br>export default function AdminRoleManagementPage() {<br>  const { user } = useAuth();<br>  if (!user || user.role !== &quot;ADMIN&quot;) {<br>    return (<br>      &lt;&gt;<br>        &lt;Navbar /&gt;<br>        &lt;AccessDeniedNotice /&gt;<br>        &lt;Footer /&gt;<br>      &lt;/&gt;<br>    );<br>  }<br>  return (<br>    &lt;&gt;<br>      &lt;Navbar /&gt;<br>      {/* admin table and actions here */}<br>      &lt;Footer /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p><strong>Reflection:</strong><br> Using the same pattern across pages makes the app feel consistent and easier to evolve, but it also requires team discipline and a bit more onboarding time.</p><h3>7. Non-Functional Wins — Testability and Robustness from Refactoring</h3><p>Some of the refactoring in this project also targets non-functional aspects such as testability and robustness, not only readability.</p><p>Two examples:</p><ol><li><strong>Injectable API services for tests</strong><br> The Curator Edit/Delete Data page can use a real services/api module in production, or an injected fake version in tests via __TEST_INJECT_SERVICES__. This allows the page to be tested without real network calls.</li><li><strong>Pure validation function</strong><br> The validateFormState function in the Curator Add Data page is a pure function that takes an input object and returns error messages. Because it does not depend on React state or the DOM, it can be unit tested quickly.</li></ol><p><strong>Example: injectable service pattern (testability)</strong></p><pre>// In tests (conceptual example)<br>(global as any).__TEST_INJECT_SERVICES__ = {<br>  registryApi: {<br>    async getDiseases() {<br>      return [{ id: 1, name: &quot;Flu Burung&quot; }];<br>    },<br>  },<br>};<br><br>// When the page runs, it will pick this fake service instead of the real one</pre><p><strong>Example: pure validation function + simple test</strong></p><pre>// validateFormState (from Curator Add Data)<br>export function validateFormState(input: {<br>  jenisPenyakit?: string;<br>  lokasi?: string;<br>  tanggal?: { dd?: string; mm?: string; yyyy?: string };<br>  sumberBerita?: string;<br>  usia?: string;<br>}) {<br>  // ...same implementation as earlier...<br>}</pre><pre>// curator-add-data/page.test.ts (example test)<br>import { validateFormState } from &quot;../curator-add-data/page&quot;;<br>test(&quot;returns error when usia is not a number&quot;, () =&gt; {<br>  const errors = validateFormState({<br>    jenisPenyakit: &quot;Flu Burung&quot;,<br>    lokasi: &quot;Jakarta&quot;,<br>    tanggal: { dd: &quot;10&quot;, mm: &quot;02&quot;, yyyy: &quot;2025&quot; },<br>    sumberBerita: &quot;Website resmi&quot;,<br>    usia: &quot;abc&quot;, // invalid<br>  });<br>  expect(errors.usia).toBe(&quot;Usia harus berupa angka&quot;);<br>});</pre><p><strong>Reflection:</strong><br> These patterns do not change what the user sees, but they make the code easier to test and less fragile. That is part of refactoring for non-functional quality, not just for nicer formatting.</p><h3>Conclusion</h3><p>By applying refactoring and simple design patterns on the frontend, the Curator pages in PantauTular became:</p><ul><li>Easier to read and understand</li><li>Better separated between layout, logic, and data access</li><li>Safer to change, because validation and API calls are isolated</li><li>More testable, thanks to pure functions and injectable services</li><li>More ready to grow, as new features can plug into the existing structure without rewriting everything</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde88611ae81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Backend QA Journey]]></title>
            <link>https://medium.com/@darren.marcello/a-practical-backend-qa-journey-b49346e8f7c3?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/b49346e8f7c3</guid>
            <category><![CDATA[quality-assurance]]></category>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 16:04:05 GMT</pubDate>
            <atom:updated>2025-11-19T16:10:59.045Z</atom:updated>
            <content:encoded><![CDATA[<p>Quality assurance in backend development is not only about making endpoints work. It involves proving that the code is safe, maintainable, and fully tested. While working on the expert_user_feature module in pantautular-be-2025, I went through a complete cycle of static analysis, security fixes, and coverage improvement until the CI pipeline finally showed a clean report.</p><p>This blog explains my process, with dedicated sections where you can attach screenshots or links as evidence.</p><h3>1. Initial Condition and Static Analysis Results</h3><blockquote><strong>Coverage on new code: 0.0%</strong></blockquote><p>When I pushed my first version of the module, the features worked correctly in manual testing. However, the static analysis results revealed several issues, including hard coded credentials and zero coverage on new code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtqWHmQJef3Q2a53mExzhA.png" /><figcaption><strong>Screenshot 1.1 SonarCloud Initial Analysis</strong></figcaption></figure><p>Static analysis plays an important role in quality assurance because it evaluates the structure, correctness, and potential risks in the code before the system is executed. This makes it a preventive form of QA that helps detect issues such as security vulnerabilities, inconsistent patterns, and code smells early in the development cycle. Unlike dynamic testing that relies on runtime behavior, static analysis ensures the internal correctness of the implementation. In my case, SonarCloud became the primary tool that enforced these checks and guided me to improve code consistency and safety.</p><h3>2. Fixing Hard Coded Passwords in Test Files</h3><p>One of the major findings was the use of static passwords inside the test suite. SonarCloud flagged this as a security risk.</p><p>To fix it, I replaced all hard coded password strings with secure, randomly generated and hashed passwords:</p><pre>from django.contrib.auth.hashers import make_password<br>import uuid<br>password = make_password(str(uuid.uuid4()))</pre><p>Why this works:</p><ul><li>No sensitive string is stored directly in the code</li><li>The value is always unique</li><li>The password is hashed following Django security standards</li></ul><p>The security hotspot was first identified through SonarCloud under the authentication category. The report highlighted multiple hard coded credentials. After reviewing the flagged lines, I created a commit that replaced all static password values with secure, hashed, randomly generated strings. This commit served as the main reference for the fix, and it was followed by another commit that updated the test suite to ensure the new password generation process worked correctly. These commits were validated through the CI pipeline before they were merged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLhUTOZeAoDPyYV0bUFa-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaJ7wZLtcXbkDozmE9u5QQ.png" /></figure><p>Link : <br><a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/890e45c8696d39597feff859f5cf6726614ba4ea">https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/890e45c8696d39597feff859f5cf6726614ba4ea</a><br><a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/890e45c8696d39597feff859f5cf6726614ba4ea">https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/890e45c8696d39597feff859f5cf6726614ba4ea</a></p><p>The coverage issue was also identified through the SonarCloud report which showed 0 percent coverage on new lines. I analyzed which functions and logical branches were untested, then added the required test cases to cover each path. Each improvement was committed progressively so that the impact on the coverage report could be tracked through the pipeline.</p><h3>3. Building a Complete Test Suite</h3><p>To reach 100 percent coverage on new lines, I created a structured test suite that covers realistic behavior of the module.</p><h4>My test coverage included :</h4><p><strong>Authorization tests :</strong></p><ul><li>preventing non owners from deleting batches</li><li>blocking unauthenticated users</li><li>returning forbidden responses for incorrect roles</li></ul><p><strong>Batch and case behavior :</strong></p><ul><li>creating new batches</li><li>uploading CSV files</li><li>listing batches owned by the logged in user</li><li>deleting a batch while keeping its cases intact</li></ul><p><strong>Negative tests :</strong></p><ul><li>invalid case or batch IDs</li><li>invalid payload formats</li><li>repeated delete operations</li></ul><p><strong>Idempotency :</strong></p><ul><li>deletion operations producing the same safe result when repeated</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM9f9SrZnyauHki5gsiWWA.png" /></figure><p>Link :<br><a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/actions/runs/19270822423/job/55098338238">https://github.com/PPL-BRIN-2025/pantautular-be-2025/actions/runs/19270822423/job/55098338238</a></p><h3>4. Final Results After Pipeline Reanalysis</h3><p>Once all fixes and test cases were completed, I reran the CI pipeline. The results showed a fully clean report.</p><p>The final outcomes were:</p><ul><li>100 percent coverage on new lines</li><li>zero security hotspots</li><li>zero new issues</li><li>zero duplication</li><li>quality gate passed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoUEdIy9DS6pHo-osCxu8Q.png" /></figure><p><strong>Link : <br></strong><a href="https://sonarcloud.io/summary/new_code?id=PPL-BRIN-2025_pantautular-be-2025&amp;pullRequest=76">https://sonarcloud.io/summary/new_code?id=PPL-BRIN-2025_pantautular-be-2025&amp;pullRequest=76</a><br><a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/b4631da8953ae38a8c26fd979529e31aa27f68e0">https://github.com/PPL-BRIN-2025/pantautular-be-2025/commit/b4631da8953ae38a8c26fd979529e31aa27f68e0</a></p><p>These measurements are not only targets to reach but also mechanisms that help the team maintain long-term project stability. A strict quality gate prevents code with security vulnerabilities or untested logic from entering the main branch. Enforcing 100 percent coverage on new code ensures that every new feature is predictable and safe. Our CI/CD pipeline integrates these checks into every pull request so the team can rely on a consistent quality baseline, reduce regression risks, and speed up the review process.</p><h3>5. Integrating QA into the Team Workflow</h3><p>The improvements I made were not only local changes. They strengthened our CI workflow. The pipeline is now able to:</p><ol><li>run test cases automatically</li><li>measure coverage and upload results</li><li>analyze code through SonarCloud</li><li>block pull requests that fail quality standards</li></ol><p>This ensures that every developer follows the same quality expectations and that potential regressions are caught early.</p><h3>6. Reflection</h3><p>Working through this end to end QA process taught me that software quality is measurable and enforceable. Static analysis and test coverage are not abstract academic topics. They are practical tools that prevent real risks in production systems.</p><p>By improving the security, test coverage, and reliability of my module, I experienced firsthand how disciplined QA can raise the standard of the entire project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b49346e8f7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Team Efficiency Through Integrated Tool Discipline in PantauTular]]></title>
            <link>https://medium.com/@darren.marcello/maximizing-team-efficiency-through-integrated-tool-discipline-in-pantautular-d8f801286ef0?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f801286ef0</guid>
            <category><![CDATA[team-work-with-tools]]></category>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 04:34:52 GMT</pubDate>
            <atom:updated>2025-11-24T15:49:36.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*6_SDgZkXpJiCzHm3.gif" /></figure><p>The <em>PantauTular</em> project connected developers, designers, and quality assurance members who collaborated to build a disease-monitoring system that supports accurate data management and public awareness. Beyond programming, this project became a study in how disciplined teamwork and synchronized tool usage improve productivity and reduce friction. Each member relied on a shared ecosystem of <strong>Git</strong>, <strong>Jira</strong>, <strong>Figma</strong>, and <strong>Koyeb</strong> to maintain alignment between planning, design, implementation, and deployment.</p><p>Throughout the development cycles, I contributed to both backend and frontend components, emphasizing transparency and traceability. Each commit, merge, and update followed an agreed workflow that ensured accountability. Our collective goal was to integrate every phase of software development into a seamless chain of tools that reinforced teamwork, improved review quality, and made every outcome measurable.</p><h4>Workflow Overview</h4><blockquote>Figma as the Design Source of Truth</blockquote><p>Before a single line of code was written, our process began in <strong>Figma</strong>. The design team created complete wireframes, user flows, and interactive mockups that reflected the requirements gathered in earlier discussions. Figma allowed us to visualize the structure of each feature and define how users would navigate the system. These designs were not static; every component had attached comments where team members could discuss layout decisions, accessibility issues, or visual consistency.</p><p>As development began, we treated Figma as a living documentation hub. Each developer referred to component names, color palettes, and spacing guidelines directly from the shared file, ensuring that frontend implementation stayed consistent with design intent. The comments feature in Figma reduced misunderstanding between designers and engineers and shortened review cycles. Design changes were versioned in real time, so even if multiple people worked on different screens, we never lost the connection between UX decisions and backend logic.</p><p>When a design reached final approval, the related link was attached to its Jira issue. This provided a direct bridge between design and development tasks. Reviewers could open the same Figma page to verify visual accuracy when testing features on staging. This workflow helped maintain coherence between <strong>requirement definition</strong>, <strong>design validation</strong>, and <strong>code implementation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Poy4Z4tjQpJu6YeNiQWPZw.png" /><figcaption>See more on <a href="https://www.figma.com/design/xhmTSjVVmrmkZl2hFq2M7C/PantauTular-Figma-Mockup?node-id=0-1&amp;p=f&amp;t=Ei3NnltFhfhvnxzy-0">https://www.figma.com/design/xhmTSjVVmrmkZl2hFq2M7C/PantauTular-Figma-Mockup?node-id=0-1&amp;p=f&amp;t=Ei3NnltFhfhvnxzy-0</a></figcaption></figure><blockquote>How Git Supported Structured Collaboration</blockquote><p>Git functioned as the central version-control system that organized every line of code in PantauTular. Each team member created branches named after their assigned Jira task (for example, PBI-64-add-curator-form), ensuring traceability between project planning and technical implementation. This made it easy for reviewers to identify what feature a branch represented. By separating branches per feature, we minimized conflicts and kept the main branch stable.</p><p>Our team applied Test-Driven Development (TDD) to maintain quality from the start. Each code change followed the RED → GREEN → REFACTOR commit pattern. In the RED phase, developers wrote tests that initially failed to define the target behavior. In the GREEN phase, they implemented the code to make the tests pass. Finally, in the REFACTOR phase, they cleaned up the implementation while keeping all tests green. This structure provided meaningful commit history and allowed others to see progress in logical steps.</p><p>Merge requests (MRs) were the focal point of collaboration. After pushing changes, developers opened an MR to request peer review. In this stage, reviewers added inline comments to highlight potential improvements or issues. No merge occurred until all comments were resolved and automated test checks passed. This ensured collective code ownership, encouraged learning through feedback, and maintained a high-quality repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*Y2tHCKJov52c7Rj1SrScBg.png" /><figcaption>Git Workflow Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*v4UexqtOFA2oTQK4_eVOkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86Ztb0hYzybRmR907CR7hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*m_QD6WXvvCyQgvMApdcnAw.png" /><figcaption>Branches in Github, Pull and Merge Request, and Review on Github</figcaption></figure><blockquote>Jira and Task Coordination</blockquote><p>Jira acted as our coordination hub where all user stories, tasks, and subtasks were created, prioritized, and tracked. During <strong>Sprint Planning</strong>, the Product Owner and team selected issues from the backlog and moved them into the “To Do” column, defining each issue’s acceptance criteria. Once a developer picked a task, its status was changed to <strong>In Progress</strong>, signaling that work had begun.</p><p>During <strong>Daily Stand-up meetings</strong>, each member updated progress in Jira to reflect what had been done and what blockers remained. This real-time visibility helped the team identify dependencies early. When development on a feature was completed, the issue status was set to <strong>In Review</strong>. At this stage, Quality Assurance (QA) members reviewed the implementation by examining the merge request, running test scenarios, and verifying alignment with requirements. If the MR was approved, the corresponding Jira issue was moved to <strong>Done</strong>. Finally, when all subtasks under a story were marked Done, the main story was also completed before the Sprint Review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*PVNSANqGzAx5icOnl9YoCw.png" /><figcaption>Jira Workflow Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dOmta1-vIeVIfZyYCXcdFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJeUzJiicmFmjtkvgv52zQ.png" /><figcaption>Our Jira : <a href="https://samuellapnadia.atlassian.net/jira/software/projects/SCRUM/boards/34/backlog?selectedIssue=SCRUM-88&amp;visitedUserSeg=true">https://samuellapnadia.atlassian.net/jira/software/projects/SCRUM/boards/34/backlog?selectedIssue=SCRUM-88&amp;visitedUserSeg=true</a></figcaption></figure><p>This structure ensured that no feature skipped any step in validation. Every change was traceable through both the Git merge request and the Jira issue, maintaining accountability from planning through release.</p><blockquote>Scrum Ceremonies and Sprint Workflow</blockquote><p>The project followed the Scrum framework to manage iterative progress. Each sprint began with a <strong>Sprint Planning</strong> meeting, where the team reviewed priorities and assigned issues from the backlog. Clear goals and definitions of “Done” were agreed upon so that everyone understood expectations. These tasks then entered the “To Do” column in Jira.</p><p>Throughout the sprint, we held <strong>Daily Meetings</strong> to synchronize progress. Each member briefly explained what they accomplished the previous day, what they planned to do next, and any blockers that required help. This ritual kept communication open and encouraged accountability while issues remained <strong>In Progress</strong>.</p><p>As features reached completion, we transitioned into <strong>Sprint Review</strong>, where the team demonstrated new functionality on the shared Koyeb staging environment. Feedback from peers and the Product Owner was recorded for improvement. Afterward, we conducted a <strong>Sprint Retrospective</strong> to reflect on what worked well, what could be improved, and which practices should continue in the next cycle. This retrospective often led to small but valuable process refinements, such as improving commit message clarity or standardizing review comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*5rABnW_O4Bmuh8Nzwk9VWg.png" /><figcaption>Sprint Workflow Diagram</figcaption></figure><p>Through these Scrum ceremonies, communication stayed structured and predictable, which kept our development aligned with project goals.</p><h4>How Tools Strengthened Teamwork</h4><p>The consistent use of tools like Jira, GitHub, and Figma significantly improved coordination among members. Every merge request served as a checkpoint for discussion, ensuring that changes were reviewed from both technical and design perspectives. This process not only caught potential errors before integration but also created a transparent history of decision-making. Each commit was small and well-documented, allowing reviewers to understand context immediately and provide targeted feedback.</p><p>Figma became the shared language between developers and designers. Instead of relying on chat messages or screenshots, we embedded Figma comment links directly in merge requests. This made it easier to align design decisions with the actual implementation and ensured that revisions were properly recorded. Jira further supported teamwork by providing real-time visibility on task progress and ownership, allowing everyone to anticipate dependencies and plan their next steps effectively.</p><p>Our coordinated workflow is reflected in cross-linked systems. For instance, the backend and frontend merge requests listed earlier were each tied to their respective Jira tickets and Figma assets. This alignment turned tool usage from a passive requirement into an active teamwork enhancer that reduced delays and improved communication accuracy.</p><h3>Issues and Lessons Learned</h3><p>As development progressed, we encountered several tool related challenges that affected integration flow and team alignment. These issues were not only technical, but also procedural, showing how even strong tools can fail without consistent discipline.</p><p><strong>Figma gaps and missing design pages.</strong><br> In one task, the Figma mockup did not fully cover the scope described in our PBI. Some supporting screens and states were missing compared to what the backlog required. This created uncertainty when implementing the feature because the design source of truth was incomplete. To resolve it, I implemented the missing pages independently by following the established design system, layout patterns, and behavior from similar screens. I also ensured the new pages stayed visually and functionally aligned with the rest of the product. This experience reinforced that developers must be capable of filling design gaps responsibly when timelines demand it, while still respecting design consistency.</p><p><strong>Jira progress was often outdated.</strong><br> Another recurring issue was that some team members forgot to update Jira statuses, sometimes even after Sprint Review had already passed. This reduced visibility during daily syncs and made task tracking less reliable. The solution was direct follow up and reminders. I reached out to members privately when their tickets were stale, and we also made public announcements in the group to reinforce the habit of updating Jira as part of the workflow, not as an optional step. Over time, this improved accountability and helped our sprint board reflect real progress.</p><p><strong>GitHub merge conflict handling caused regression.</strong><br> A major frustration I faced was when my work had already been pushed and merged into the staging branch, but later a teammate encountered a merge conflict and did not review it properly. Instead of resolving the conflict carefully, the merge effectively reverted parts of my completed work back to an earlier state. The result was that features I had finished no longer appeared in staging, even though the merge history showed they had been integrated before. We handled this by re checking the conflict source, restoring the lost changes, and emphasizing review discipline when resolving conflicts. This incident showed that merge conflicts are not just a technical problem, but also a communication and responsibility issue.</p><p><strong>Evaluation of the workflow implementation.</strong><br> Overall, our integrated workflow worked well when every member followed it consistently. The cross linking between Jira issues, GitHub branches and merge requests, and Figma mockups created strong traceability. It reduced duplicated work and made reviews faster because context was always attached to the task. The staging deployment flow through Koyeb also supported shared validation and helped us catch issues early.</p><p>However, the workflow was still sensitive to weak discipline. When Figma designs were incomplete, Jira updates were ignored, or merge conflicts were handled without proper review, the toolchain lost its value and introduced delays. This showed that the workflow design itself was solid, but its effectiveness depended heavily on team habits. Once we started reinforcing reminders, reaching out earlier, and treating tool updates as mandatory communication, implementation became smoother and more reliable.</p><p><strong>Lessons learned.</strong><br> From these challenges, I learned that tool integration only works when everyone applies the same discipline. Figma must stay complete and aligned with PBIs, Jira updates must be treated as a real time communication contract, and GitHub conflict resolution must be handled with careful review, not rushed merging. Most importantly, I realized that the strongest safeguard across all tools is communication. When design is unclear, progress is invisible, or conflicts happen, the fastest and safest fix comes from active coordination and checking with each other. The tools supported our workflow, but communication kept the workflow alive.</p><h4>Making the Tools Work Harder</h4><p>To ensure full-cycle efficiency, I worked on connecting the entire workflow across tools. Every Jira issue key was referenced in corresponding branch names and pull request titles, allowing instant traceability from requirements to deployed code. Each successful merge triggered an automatic deployment to Koyeb, ensuring that no local discrepancies could interfere with team testing. This continuous integration approach made it possible to catch bugs early and evaluate performance directly on a shared environment.</p><p>Beyond automation, I also prioritized feedback visibility. Whenever a merge request introduced a visual or behavioral change, I attached screenshots and Figma component links so reviewers could see both technical and design alignment. This habit accelerated peer review and strengthened mutual accountability. On the backend side, I contributed by ensuring that Docker health checks and environment configurations were consistent across services, reducing downtime during deployments.</p><p>This integration of tools is demonstrated in the connected ecosystem of Jira tickets, GitHub merge requests, and Figma design references mentioned above. Each link represents not just evidence of work but a deliberate attempt to connect planning, implementation, and verification into one continuous workflow.</p><h4>Reflection</h4><p>At the beginning of this project, I was mainly aware of how these tools functioned individually. However, through practical experience, I learned that the real value of teamwork lies in how these tools are integrated and used with discipline. Each merge request, Jira update, and Figma revision served as a feedback loop that improved team synchronization and accountability. By combining structured planning, transparent communication, and shared validation environments, we achieved smoother coordination and measurable productivity gains.</p><p>This project proved that tool integration is not merely technical convenience but an essential part of professional collaboration. The ability to trace a single requirement from planning to deployment gave our team confidence and consistency. Most importantly, the process demonstrated that effective teamwork grows not from the number of tools used, but from how purposefully they are applied to connect people, processes, and results.</p><h4>Appendix</h4><p>Link Merge on Github :</p><ul><li>Backend contributions:<br>https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/35 <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/37">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/37</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/46">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/46</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/47">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/47</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/59">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/59</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/63">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/63</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/64">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/64</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/66">https://github.com/PPL-BRIN-2025/pantautular-be-2025/pull/66</a></li><li>Frontend contributions:<br>https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/5 <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/11">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/11</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/12">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/12</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/18">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/18</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/20">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/20</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/24">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/24</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/33">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/33</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/39">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/39</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/47">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/47</a> <a href="https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/48">https://github.com/PPL-BRIN-2025/pantautular-fe-2025/pull/48</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJeUzJiicmFmjtkvgv52zQ.png" /><figcaption><a href="https://samuellapnadia.atlassian.net/jira/software/projects/SCRUM/boards/34/backlog?selectedIssue=SCRUM-88&amp;visitedUserSeg=true">https://samuellapnadia.atlassian.net/jira/software/projects/SCRUM/boards/34/backlog?selectedIssue=SCRUM-88&amp;visitedUserSeg=true</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Poy4Z4tjQpJu6YeNiQWPZw.png" /><figcaption><a href="https://www.figma.com/design/xhmTSjVVmrmkZl2hFq2M7C/PantauTular-Figma-Mockup?node-id=0-1&amp;p=f&amp;t=Ei3NnltFhfhvnxzy-0">https://www.figma.com/design/xhmTSjVVmrmkZl2hFq2M7C/PantauTular-Figma-Mockup?node-id=0-1&amp;p=f&amp;t=Ei3NnltFhfhvnxzy-0</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*fQl03Euui9Z_Wja9.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f801286ef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering Secure Features End-to-End: From React UI Guards to Django API Controls]]></title>
            <link>https://medium.com/@darren.marcello/engineering-secure-features-end-to-end-from-react-ui-guards-to-django-api-controls-968ae9d373e5?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/968ae9d373e5</guid>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 06:33:21 GMT</pubDate>
            <atom:updated>2025-11-06T02:21:10.715Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Secure Programming Matters</h4><p>Security isn’t a layer you glue on later, it shapes how data flows, who can touch it, and how the app behaves when something goes wrong. In this project, I treated security as a first-class concern across the stack:</p><ul><li><strong>Front-end</strong>: role gating, safe inputs, explicit error states.</li><li><strong>Back-end</strong>: authentication/authorization, safe serialization, atomic transactions, immutable audit data.</li><li><strong>Quality assurance</strong>: negative tests (401/403/400/404), error-handling assertions, and unit tests for auth routines.</li></ul><p>Below I map my work to the rubric’s four points and show concrete code + tests.</p><h4>What OWASP Means and How It Works</h4><p>The <strong>Open Web Application Security Project (OWASP)</strong> is a globally recognized nonprofit organization focused on improving software security. It provides developers with open, community-maintained resources such as the <strong>OWASP Top 10</strong>, a regularly updated list of the most critical web-application security risks. These risks, ranging from broken authentication and access control to sensitive-data exposure and injection attacks, serve as a practical checklist for secure coding. In this project, OWASP principles guided how I analyzed vulnerabilities and structured defenses. For instance, I mitigated <em>Broken Authentication</em> and <em>Broken Access Control</em> through strict JWT validation and role-based permission classes; <em>Sensitive Data Exposure</em> by excluding confidential fields from serializers; and <em>Integrity Violations</em> by using atomic transactions. By aligning implementation choices with OWASP’s categories, the codebase not only met functional goals but also achieved measurable resilience against real-world attack vectors.</p><h4>OWASP Top 10 Principles</h4><p>To provide a more structured understanding, the <strong>OWASP Top 10 (2021)</strong> highlights the ten most critical web application security risks. These principles serve as a checklist and threat model throughout development, from design to deployment. Below are the ten categories I used as my reference when assessing the PantauTular project:</p><ol><li><strong>Broken Access Control</strong> — restricting user permissions properly to prevent unauthorized actions.</li><li><strong>Cryptographic Failures</strong> — ensuring sensitive data such as passwords and tokens are securely stored and transmitted.</li><li><strong>Injection</strong> — validating and sanitizing all input to prevent injection attacks (e.g., SQL injection, XSS).</li><li><strong>Insecure Design</strong> — embedding security from the start through validation, rate limiting, and safe workflows.</li><li><strong>Security Misconfiguration</strong> — configuring servers and frameworks safely, with debug mode off and proper error responses.</li><li><strong>Vulnerable and Outdated Components</strong> — keeping dependencies up to date and auditing them for known vulnerabilities.</li><li><strong>Identification and Authentication Failures</strong> — ensuring authentication logic cannot be bypassed and sessions/tokens are validated correctly.</li><li><strong>Software and Data Integrity Failures</strong> — protecting against tampering through atomic transactions, code signing, and immutable audit logs.</li><li><strong>Security Logging and Monitoring Failures</strong> — recording and monitoring key events such as failed logins and admin actions.</li><li><strong>Server-Side Request Forgery (SSRF)</strong> — preventing servers from making unintended requests to internal or malicious endpoints.</li></ol><p>In my project, at least half of these categories were directly addressed in code, including Broken Access Control, Authentication Failures, Cryptographic Safety, Data Integrity, and Error Handling, while others such as dependency audits and logging will be reinforced in later iterations. This alignment ensured that secure programming was not just theoretical but embedded into every layer of the system.</p><blockquote>1) Threat &amp; Risk Analysis (Understanding potential threats)</blockquote><h4>App surface &amp; risks I considered</h4><ul><li><strong>Broken Authentication / Access Control (OWASP)</strong><br> Risks: using endpoints without valid tokens; non-admin accessing admin routes; non-expert deleting others’ batches; privilege escalation through weak role checks.</li><li><strong>Injection / Malformed Input</strong><br> CSV upload rows with unexpected values; URLs with invalid formats; over-posting fields in JSON bodies.</li><li><strong>Sensitive Data Exposure</strong><br> Accidentally returning passwords or internal tokens in API responses.</li><li><strong>Integrity / Consistency Failures</strong><br> Partial writes during CSV upload (some rows saved, some failed); tampering with historical logs.</li><li><strong>Improper Error Handling</strong><br> Leaking stack traces; inconsistent status codes that confuse clients or help attackers.</li></ul><h4>Specific attack/abuse scenarios</h4><ul><li><strong>EXP_USER batch deletion</strong>: user tries to delete another user’s batch (must be blocked).</li><li><strong>Admin list/change role</strong>: non-admin tries to hit /admin-feature/users or change roles.</li><li><strong>CSV upload</strong>: upload without file; corrupt header; row validation failure mid-transaction (must atomically rollback).</li><li><strong>URL fields</strong>: supply non-URL strings to bypass source attribution logic.</li><li><strong>Audit trails</strong>: post-facto editing or deleting log entries to hide tracks (must be blocked by DB trigger).</li></ul><blockquote>2) Security Standards Implemented (Authentication &amp; Authorization, BE+FE)</blockquote><h4>Backend: Authentication &amp; Role-based Authorization</h4><p><strong>Permissions are segregated</strong> and easy to reason about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Vto9E1MBMnXqugxnfyG0w.png" /><figcaption>authentication/permissions.py</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*13LfQrAAQd-D_oNdahtTlQ.png" /><figcaption>expert_user_feature/permissions.py</figcaption></figure><p>All expert routes share a single base with consistent auth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*q0kMVEjlhbd9JAPeNwhWMg.png" /><figcaption>expert_user_feature/views_base.py</figcaption></figure><p><strong>Why it matters (OWASP):</strong></p><ul><li>Broken Auth → mitigated by CustomJWTAuthentication + token presence/validation.</li><li>Broken Access Control → mitigated by role checks per route (IsExpertUserRole, admin role for admin endpoints).</li></ul><h4>Backend: Principle of Least Privilege in queries</h4><p>Only the owner can see or delete their batches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*sijwNayZRlZa9wIlviqBIg.png" /><figcaption>expert_user_feature/views.py</figcaption></figure><h4>Backend: Safe Serialization (no sensitive fields)</h4><p>Users are returned <strong>without</strong> password fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*tVjx4L8H_POau0bXIvXsIQ.png" /><figcaption>admin_feature/serializers.py</figcaption></figure><p><strong>Why it matters (OWASP Sensitive Data Exposure):</strong> You never serialize secrets by accident.</p><h4>Backend: Atomicity &amp; Data Integrity for uploads</h4><p><strong>All CSV rows</strong> are processed in one transaction. If any row fails, <strong>everything rolls back</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*eZvS9JjSTaONsxuSWljh3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*mZG7VkXc8QKENB4yFF4vXw.png" /><figcaption>expert_user_feature/views.py (CSV upload)</figcaption></figure><p><strong>Why it matters (Integrity):</strong> prevents partial datasets.</p><h4>Backend: Immutable audit trail (tamper-resistant)</h4><p>A Postgres trigger <strong>blocks UPDATE/DELETE</strong> on a log table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*nfeiqJk65xDAMi-GT8PebA.png" /><figcaption>curator_feature/migrations/0006_curatordatalog_immutable.py</figcaption></figure><p><strong>Why it matters:</strong> auditable, non-repudiable changes.</p><h4>Front-end: Role gate &amp; safe inputs</h4><p>Pages check <strong>allowed roles</strong> and render <strong>AccessDenied</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*JQ3iX1g_awvU9Dv0SnY2-A.png" /><figcaption>curator-add-data/page.tsx</figcaption></figure><p>Strict URL validation on the client (helps UX, <strong>does not replace server-side validation</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckyIEOUK2Us92K7UDO9wzw.png" /><figcaption>curator-add-data/page.tsx</figcaption></figure><p><strong>Why it matters (OWASP)</strong>: FE guards reduce accidental misuse; BE remains the source of truth.</p><blockquote>3) Applying Secure Programming Standards (OWASP) + Testing</blockquote><h4>OWASP-aligned practices present</h4><ul><li>Broken Auth/Access Control → role permissions (IsTokenAuthenticated, IsExpertUserRole, Admin-only serializers/views), query scoping to uploaded_by.</li><li>Sensitive Data Exposure → serializers exclude passwords.</li><li>Integrity/Consistency → transaction.atomic() in CSV uploads.</li><li>Improper Error Handling → consistent 400/401/403/404/500 responses; no stack traces.</li><li>Auditability → admin actions logged; curator datalog immutable via DB trigger.</li></ul><h4>Negative &amp; positive tests (evidence)</h4><p>Auth/unit tests exercise error paths and DB faults safely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*zjFtoK-ex1t1Hdy_CaHr3w.png" /><figcaption>authentication/tests/test_security.py</figcaption></figure><p><strong>Why it matters:</strong> tests don’t just prove “it works”, they prove <strong>unsafe paths are blocked</strong>.</p><blockquote>4) SDLC-Level Security Considerations (beyond code)</blockquote><p>What I analyzed and how I’d (or did) address it:</p><ul><li><strong>Commit integrity &amp; authorship</strong><br> <em>Risk:</em> tampered commits or spoofed authors.<br> <em>Mitigation:</em> enable <strong>GPG commit signing</strong>, require “verified” signatures in PRs.</li><li><strong>Secrets management</strong><br> <em>Risk:</em> leaking JWT secrets/API keys in source control.<br> <em>Mitigation:</em> .env files excluded; use CI-scoped secrets; rotate keys.</li><li><strong>Dependency risk</strong><br> <em>Risk:</em> vulnerable libs.<br> <em>Mitigation:</em> add CI jobs for pip-audit/safety and npm audit; pin versions; renovate/bot for updates.</li><li><strong>CI/CD integrity</strong><br> <em>Risk:</em> pipelines altering artifacts; unsafe env injection.<br> <em>Mitigation:</em> per-env secrets, protected branches, least-privilege CI tokens.</li><li><strong>Runtime hardening</strong><br> <em>Risk:</em> verbose errors in production; CORS misconfig; missing throttling.<br> <em>Mitigation:</em> production settings lock-down, safe error pages, CORS allowlist; DRF throttling for auth-heavy endpoints.</li><li><strong>Data lifecycle</strong><br> <em>Risk:</em> mutating audit history.<br> <em>Mitigation:</em> your <strong>immutable trigger</strong> is already in place, keep it for any log/ledger tables.</li></ul><h3>Reflection</h3><p>Through this project, I learned that secure programming is not just about adding layers of protection but about designing each part of the system with security as its foundation. Every decision, from restricting access with precise permission classes to validating every input on both the frontend and backend, shapes how resilient the application becomes against real threats. Implementing consistent authentication and authorization with CustomJWTAuthentication, role-based controls, and ownership-based queries showed me the importance of the principle of least privilege in practice. Meanwhile, features like safe serialization, atomic transactions, and immutable audit logs demonstrated how reliability and security go hand in hand. Writing targeted tests for 401, 403, and 404 responses made me more aware of the value of defensive coding, ensuring that failures happen safely and predictably. This experience deepened my understanding that security is part of the entire SDLC, covering design, implementation, testing, and deployment, and that a truly secure system is one where every layer anticipates and gracefully handles what could go wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968ae9d373e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging Administrative Control and Curator Insight]]></title>
            <link>https://medium.com/@darren.marcello/bridging-administrative-control-and-curator-insight-e1fca32f16b1?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1fca32f16b1</guid>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 06:32:56 GMT</pubDate>
            <atom:updated>2025-11-24T07:53:37.003Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Comparative Usability and Visual Design Evaluation in the PantauTular System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*OsR0f9B5Fd8Pv6Vo.gif" /></figure><blockquote><strong>1. Introduction</strong></blockquote><p>This blog documents my experience designing and implementing two major modules in the PantauTular project:<br>(1) the <strong>Admin Role Management page</strong>, and<br>(2) the <strong>Curator Add Data page</strong>.</p><p>Both were developed using <strong>React + TypeScript</strong> and <strong>Tailwind CSS</strong>, focusing on usability heuristics, accessibility, and production-grade functionality. Each interface evolved from a wireframe mockup and progressively aligned with <strong>Nielsen’s 10 Usability Heuristics</strong>.</p><p>While the Admin Role Management page aimed for clarity and user control, the Curator Add Data page emphasized system feedback, error handling, and backend integration.</p><blockquote>2. Wireframe &amp; Mockup Foundation</blockquote><p>I contributed to the <strong>wireframe and mockup preparation</strong> for both pages using low-fidelity sketches and mid-fidelity prototypes.<br>Below is an excerpt of the conceptual layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*M5D-FqbZNqcUG8ZrMmUKUA.png" /><figcaption>Admin Role Management Wireframe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*0ytFuvJA-1fIb-LkyeNvhA.png" /><figcaption>Curator Add Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*3W0ZG3PstU4VubIYAwbGIA.png" /><figcaption>Curator Edit Delete Data</figcaption></figure><blockquote><strong>3. Admin Role Management Page</strong></blockquote><p><strong>a. Core Implementation</strong></p><pre>export default function AdminRolePage() {<br>  const [users, setUsers] = useState&lt;User[]&gt;([]);<br>  const [error, setError] = useState(&quot;&quot;);<br>  const [success, setSuccess] = useState(&quot;&quot;);<br>  <br>  useEffect(() =&gt; {<br>    fetch(`${API_BASE}/users`)<br>      .then(res =&gt; res.json())<br>      .then(setUsers)<br>      .catch(() =&gt; setError(&quot;Failed to load users.&quot;));<br>  }, []);</pre><p>This component handles dynamic data rendering and feedback display for all CRUD operations.</p><blockquote><strong>4. Curator Add Data Page</strong></blockquote><p>This page builds on the same heuristic principles but extends to <strong>real-time data interaction</strong> and <strong>API integration</strong>.</p><p><strong>a. Access and Role Validation</strong></p><pre>if (!user || user.role !== &quot;CURATOR&quot;) {<br>  return &lt;AccessDeniedNotice /&gt;;<br>}</pre><p>Ensures that access control is visually communicated (Heuristic #1 and #2).</p><p><strong>b. Dynamic Form Validation</strong></p><pre>if (!jenisPenyakit) next.jenisPenyakit = &quot;Jenis penyakit wajib diisi.&quot;;<br>if (!lokasi) next.lokasi = &quot;Lokasi wajib diisi.&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAadC8U49nl0Mu3Vcmsl6A.png" /></figure><p>Prevents form submission errors and provides immediate, localized feedback.</p><p><strong>c. Live Data Fetching</strong></p><pre>const remoteDiseases = await svc.registryApi.getDiseases();<br>setJenisList(remoteDiseases.map(d =&gt; d.name));</pre><p>Makes backend data visible in the UI and reduces manual typing (Heuristics #1 and #6).</p><p><strong>d. Feedback and Success State</strong></p><pre>setSuccessMessage(&quot;Data berhasil disimpan.&quot;);<br>setTimeout(() =&gt; setSuccessMessage(&quot;&quot;), 4000);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHYZswmkyUns2MkH0-pwbg.png" /></figure><p>Gives temporal feedback after successful submissions.</p><blockquote><strong>5. Applying Nielsen’s 10 Usability Heuristics</strong></blockquote><p><strong>1. Visibility of System Status</strong></p><p>Both pages immediately communicate success or failure states to users.</p><pre>{success &amp;&amp; &lt;div className=&quot;text-green-600&quot;&gt;{success}&lt;/div&gt;}<br>{error &amp;&amp; &lt;div className=&quot;text-red-600&quot;&gt;{error}&lt;/div&gt;}<br><br>setSuccessMessage(&quot;Data berhasil disimpan.&quot;);<br>setTimeout(() =&gt; setSuccessMessage(&quot;&quot;), 4000);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHYZswmkyUns2MkH0-pwbg.png" /></figure><p>The Admin page shows instant feedback after PUT/DELETE actions, while the Curator page displays confirmation modals and temporary success alerts after submission. This transparency keeps users informed about system status in real time.</p><p><strong>2. Match Between System and the Real World</strong></p><p>Labels and field names use intuitive, localized language understood by Indonesian users</p><pre>&lt;th&gt;Nama&lt;/th&gt;&lt;th&gt;Email&lt;/th&gt;&lt;th&gt;Peran&lt;/th&gt;&lt;th&gt;Aksi&lt;/th&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0T2rESsSOd8dk5gWYK8ZQ.png" /></figure><p>By using natural Bahasa Indonesia terms, both pages follow real-world conventions and reduce cognitive load.</p><p><strong>3. User Control and Freedom</strong></p><p>Users can undo or cancel potentially destructive actions.</p><pre>onClick={() =&gt; window.confirm(&quot;Apakah Anda yakin ingin menghapus pengguna ini?&quot;)}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b17lCmTAWqRoPB_1pNRbKg.png" /></figure><p>The Admin page includes confirmation dialogs before deletion, while the Curator page offers “Batal” and “Terapkan” buttons to cancel or confirm submissions, enabling safe reversibility.</p><p><strong>4. Consistency and Standards</strong></p><p>Button color conventions and icons are reused across pages (bg-blue-600 for primary, bg-red-500 for destructive).</p><pre>&lt;button className=&quot;bg-blue-600 text-white&quot;&gt;Ubah&lt;/button&gt;<br>&lt;button className=&quot;bg-red-500 text-white&quot;&gt;Hapus&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*1ujvO2ynh4JcoZbPUysnQA.png" /></figure><p><strong>5. Error Prevention</strong></p><p>Form validation and button-state control prevent invalid input.</p><pre>if (!input.jenisPenyakit)<br>  next.jenisPenyakit = &quot;Jenis penyakit wajib diisi.&quot;;<br>if (input.usia &amp;&amp; !/^\d+$/.test(input.usia))<br>  next.usia = &quot;Masukkan usia yang valid.&quot;;<br><br>&lt;button disabled={!isDirty}&gt;Terapkan&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYZgbByBV4BNeZlDK1bB2A.png" /></figure><p>Inline validators on the Curator form stop incorrect submissions, while the Admin page disables “Terapkan” when no changes exist, reducing system errors before they occur.</p><p><strong>6. Recognition Rather Than Recall</strong></p><p>Roles are selectable via dropdown rather than typed manually.</p><pre>&lt;select value={role}&gt;<br>  &lt;option&gt;ADMIN&lt;/option&gt;<br>  &lt;option&gt;CURATOR&lt;/option&gt;<br>  &lt;option&gt;VIEWER&lt;/option&gt;<br>&lt;/select&gt;<br><br>&lt;select value={jenisPenyakit}&gt;<br>  {jenisList.map(j =&gt; &lt;option key={j}&gt;{j}&lt;/option&gt;)}<br>&lt;/select&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBHGdJGMzc_37gjvcyEoxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*XnE0THE2tGMDhShyGkj6UA.png" /></figure><p>Users can pick roles or diseases from curated lists instead of typing manually. This design minimizes recall effort and aligns with form-based data entry standards.</p><p><strong>7. Flexibility and Efficiency of Use</strong></p><p>Reusable components and batch actions accelerate expert workflows.</p><pre>&lt;input type=&quot;checkbox&quot; onChange={toggleAll} /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*XnE0THE2tGMDhShyGkj6UA.png" /><figcaption>Example of dynamic dropdown lists that pre-load recent data from Curator Add data</figcaption></figure><p>Admins can bulk-select users for updates, while curators benefit from dynamic dropdown lists that pre-load recent data, improving speed for frequent users.</p><p><strong>8. Aesthetic and Minimalist Design</strong></p><p>The interface balances whitespace and contrast for readability.</p><pre>&lt;div className=&quot;bg-[#f9fafb] p-6 rounded-lg shadow-sm&quot;&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHWKCuN-nqd6BDAjT_EhvQ.png" /><figcaption>Admin Role Management</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsQ1s6GgpkmqUuRBP7tUTg.png" /><figcaption>Curator Add Data</figcaption></figure><p>Neutral colors (#f9fafb, #0069cf) and clear spacing help users focus on primary tasks, editing roles or submitting disease cases, without visual noise.</p><p><strong>9. Help Users Recognize, Diagnose, and Recover from Errors</strong></p><p>Clear, human-readable error messages guide user recovery.</p><pre>catch(() =&gt;<br>  setError(&quot;Tidak dapat memuat data pengguna. Silakan coba lagi.&quot;)<br>);</pre><p>When network requests fail, users see direct explanations in plain language rather than codes, supporting smooth recovery and reducing frustration.</p><p><strong>10. Help and Documentation</strong></p><p>A collapsible Help section and contextual hints support learning.</p><pre>{showHelp &amp;&amp; (<br>  &lt;aside className=&quot;border p-3 bg-blue-50 text-sm&quot;&gt;<br>    &lt;h3&gt;Panduan&lt;/h3&gt;<br>    &lt;p&gt;Gunakan tombol &quot;Ubah&quot; untuk mengedit peran pengguna.&lt;/p&gt;<br>  &lt;/aside&gt;<br>)}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ohlBk4zjOYMII0bY1dLEA.png" /><figcaption>Example Guidance for Add Data Location</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*g1iG8oi7zWyRVg4qa9uJIQ.png" /><figcaption>Example Help panel on Admin Role Management</figcaption></figure><p>The Admin page includes a Help panel, while the Curator page embeds short placeholder hints (e.g., <em>contoh: Jakarta, 2024–05–21</em>) for field guidance — reducing reliance on external manuals.</p><blockquote>6. Benchmarking and Evaluation</blockquote><p>To evaluate whether the Admin Role Management and Curator Add Data pages meet real-world public-sector usability expectations, I conducted a visual and structural benchmark against one of Indonesia’s most established citizen-reporting systems: <br><strong>Lapor.go.id <br>(</strong><a href="https://www.lapor.go.id/">https://www.lapor.go.id/</a>). <br>This comparison focused on layout clarity, cognitive load, trust elements, field hierarchy, and error-prevention mechanisms.</p><p>This benchmark helped reveal how PantauTular performs relative to a mature government-facing platform, while also highlighting improvement areas to make the interface more intuitive and user-friendly.</p><h4>Comparison Overview</h4><p>Below are the two reference screenshots used for analysis:</p><h4>Reference: Lapor.go.id Submission Page</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ot1ioBkXg0DTbSqdrZfrg.png" /><figcaption><a href="https://www.lapor.go.id/">https://www.lapor.go.id/</a></figcaption></figure><h4>PantauTular — Curator Add Data Page</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsQ1s6GgpkmqUuRBP7tUTg.png" /></figure><h3>What Lapor.go.id Does Well</h3><ul><li>Uses a <strong>guided, linear form flow</strong> that matches how users naturally provide information.</li><li>Displays fields in <strong>small, controlled groups</strong>, reducing cognitive load.</li><li>Applies strong <strong>visual hierarchy</strong> with consistent spacing and large breathing room.</li><li>Provides clear <strong>trust signals</strong>, such as anonymity options and gentle user guidance.</li><li>Keeps dropdowns short and structured, minimizing scrolling and confusion.</li><li>Maintains predictable microinteractions, making the interface feel stable and easy to follow.</li></ul><h3>Where PantauTular Differs</h3><ul><li>Shows <strong>all input fields at once</strong> on a single long page, making the form feel denser.</li><li>Hierarchy between elements is flatter, so critical fields do not stand out.</li><li>Dropdowns for diseases and locations are long, ungrouped, and sometimes contain duplicates.</li><li>Trust cues such as privacy notes, field explanations, or best-practice hints are minimal.</li><li>Error prevention and validation are strong, but lack a final summary or preview step.</li><li>Feedback exists, but the workflow would benefit from more microinteractions such as autosave or progress indication.</li></ul><blockquote>7. What PantauTular Can Improve</blockquote><p>To align closer with the clarity and user-friendliness demonstrated by Lapor.go.id, these improvements are recommended:</p><h3>Structural &amp; Visual Improvements</h3><ul><li>Break long forms into <strong>clearer grouped sections</strong> or collapsible segments.</li><li>Strengthen <strong>visual hierarchy</strong> using spacing, headers, and emphasis on critical fields.</li><li>Introduce a lighter <strong>guided flow</strong>, reducing the feeling of facing all fields at once.</li></ul><h3>Dropdown &amp; Data Improvements</h3><ul><li><strong>Group long dropdown lists</strong> (e.g., province → city).</li><li>Normalize disease names to remove duplicates.</li><li>Reduce excessive scrolling inside dropdowns.</li></ul><h3>Trust &amp; Guidance Enhancements</h3><ul><li>Add short <strong>inline hints</strong> and contextual microcopy for better clarity.</li><li>Include small <strong>privacy or data accuracy reminders</strong> to increase user confidence.</li><li>Provide lightweight tooltips for fields that require interpretation.</li></ul><h3>Interaction &amp; Feedback Improvements</h3><ul><li>Add <strong>autosave</strong> or draft-saving features for long inputs.</li><li>Consider a <strong>progress indicator</strong> for multi-part workflows.</li><li>Use <strong>toast notifications</strong> instead of static, layout-shifting messages.</li><li>Add a <strong>final validation summary</strong> or optional preview before submission.</li></ul><blockquote>8. Conclusion</blockquote><p>By developing and evaluating both <strong>Admin Role Management</strong> and <strong>Curator Add Data</strong> pages, I moved from wireframe sketches to a comprehensive, heuristic-driven system. The Admin interface established foundational usability through structure, hierarchy, and error prevention. The Curator interface extended those principles into real-time, backend-connected workflows with dynamic feedback.</p><blockquote>9. Appendix</blockquote><h4>Admin Role Management</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbj5ld217lLwnt0AZUOt9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Sh0zsnnLO6pr_x3M4AC6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISMh-08zJOTla8iQc80GWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj7C3_IVnsfT68pSXxYw7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DS34nv91yW60VySRqY3taQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2stbwo2S5tVtsA2p-q9J_A.png" /></figure><h4>CRUD Curator (Add and Delete)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Hu6VCAftELzPhhfLS6sSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXFr2hvpy6g_D5k_F0ha1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZUBgSmVqsLlXeiSnJXbTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3OubdwEtIMNVH8m_6EeGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0WMv2N9YmWVr0koqyolOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMjH8EQIiXxi7whcLfhj0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4QxYncVm4nazKTOCps8Vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*tuxuHJiiMmKnvbm3krY4MA.png" /></figure><h4>EXP_USER CRUD</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCFRPzq585ao0HDU5JAAMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6aCVc1YEE5haI9SsAYbSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*suywGg8PdZGOrodz.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1fca32f16b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolating Tests with Mock Objects and Stubs in Jest]]></title>
            <link>https://medium.com/@darren.marcello/isolating-tests-with-mock-objects-and-stubs-in-jest-79c129275eeb?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c129275eeb</guid>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 08:32:39 GMT</pubDate>
            <atom:updated>2025-11-11T08:03:23.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The Problem of Unstable Tests</h3><p>During the earlier sprint of <em>PantauTular</em>, I faced several unstable test cases in the frontend repository. These failures happened not because the logic was wrong, but because the tests relied on live components and real API responses. For instance, some tests failed when the backend was not reachable or when asynchronous calls returned slower than expected.</p><p>To solve this, I focused on <strong>isolating the tests</strong> using <strong>mock objects</strong> and <strong>stubs</strong>. This approach allowed me to simulate dependencies such as components and API modules while ensuring predictable, repeatable test outcomes.</p><h3>2. Understanding Mock vs Stub and AI Support</h3><p>Before implementing mocks and stubs, I needed to clearly understand the difference:</p><ul><li>A <strong>mock</strong> replaces a real dependency (component or module) and defines its behavior during the test.</li><li>A <strong>stub</strong> provides controlled input data for the test, ensuring consistent and repeatable conditions.</li></ul><p>In __tests__/curator-add-data/page.test.tsx, I used both patterns.</p><pre>// __tests__/curator-add-data/page.test.tsx<br>jest.mock(&#39;@/components/layout/Navbar&#39;, () =&gt; () =&gt; &lt;div&gt;Mocked Navbar&lt;/div&gt;);<br>jest.mock(&#39;@/components/layout/Footer&#39;, () =&gt; () =&gt; &lt;div&gt;Mocked Footer&lt;/div&gt;);<br>jest.mock(&#39;@/services/api&#39;, () =&gt; ({<br>  registryApi: {<br>    createDisease: jest.fn(),<br>  },<br>}));</pre><p>This section of the test replaces:</p><ul><li>The <strong>Navbar</strong> and <strong>Footer</strong> layout components so that visual rendering does not interfere with the logic under test.</li><li>The <strong>API module</strong> so that no real network request runs during testing.</li></ul><p>I then created stub data that mimicked user input for the form modal:</p><pre>const stubInput = {<br>  diseaseName: &#39;Test Disease&#39;,<br>  description: &#39;Sample test description&#39;,<br>  source: &#39;Health Organization&#39;<br>};</pre><p>These controlled values made the tests deterministic and removed the need for real user input or backend availability.</p><p>This stage also demonstrated my ability to apply AI support effectively. Initially, ChatGPT suggested mock patterns such as jest.fn().mockResolvedValue() but used generic paths like ‘./api’. I refined them into real project paths (‘@/services/api’) and updated function names to match our actual module (registryApi.createDisease). This ensured the mocks worked properly with our real folder structure</p><h3>3. Understanding the Need for Mocks and Stubs and Refining AI Assistance</h3><p>Using mocks and stubs solved three key problems in the testing workflow:</p><ol><li><strong>Test Stability:</strong><br> Real API requests were replaced with simulated ones, preventing random failures caused by backend unavailability.</li><li><strong>Faster Execution:</strong><br> Without waiting for actual API responses, tests ran almost instantly, which improved CI/CD speed.</li><li><strong>Controlled Scenarios:</strong><br> By mocking specific return values, I could test both success and failure states predictably.</li></ol><p>Example refinement (AI version vs final working version):</p><pre>// AI suggestion (generic)<br>jest.mock(&#39;./api&#39;, () =&gt; ({<br>  postData: jest.fn().mockResolvedValue({ message: &#39;ok&#39; }),<br>}));<br><br>// Refined version used in project<br>jest.mock(&#39;@/services/api&#39;, () =&gt; ({<br>  registryApi: {<br>    createDisease: jest.fn().mockResolvedValue({ success: true }),<br>  },<br>}));</pre><p>Originally, the AI suggested mocking a generic function api.postData(). I corrected this by aligning it with our project’s actual implementation (registryApi.createDisease) inside services/api.ts.</p><p>This refinement ensured that mocks accurately represented how the application really communicates with the backend.</p><h3>4. Understanding and Applying Mocks &amp; Stubs</h3><p>To ensure consistent test data, I created a reusable stub factory:</p><pre>function addSumber() {<br>  return {<br>    diseaseName: &#39;Mocked Source&#39;,<br>    description: &#39;Generated through stub for repeatable testing&#39;,<br>    source: &#39;Mock API Dataset&#39;<br>  };<br>}<br><br>test(&#39;uses stubbed form input for consistent data&#39;, async () =&gt; {<br>  const input = addSumber();<br>  render(&lt;CuratorAddDataPage /&gt;);<br>  fireEvent.change(screen.getByPlaceholderText(&#39;Disease Name&#39;), {<br>    target: { value: input.diseaseName },<br>  });<br>  expect(screen.getByDisplayValue(&#39;Mocked Source&#39;)).toBeInTheDocument();<br>});</pre><p>This pattern abstracts input setup into a separate stub function, ensuring consistent test data across multiple scenarios. AI originally suggested hardcoded values, but I improved it by modularizing them into a factory function, reducing duplication and improving clarity.</p><h3>5. Advanced Techniques for High-Complexity Dependencies (API Example)</h3><p>The mock target registryApi.createDisease from your actual services/api.ts looks like this:</p><pre>// services/api.ts<br>export const registryApi = {<br>  createDisease: async (data) =&gt; {<br>    const response = await fetch(`${API_URL}/disease`, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(data),<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    });<br>    return await response.json();<br>  },<br>};</pre><p>If left unmocked, this function performs a real network call during testing.<br> To handle this high-complexity dependency, I used Jest’s mock to intercept it entirely:</p><pre>(registryApi.createDisease as jest.Mock).mockResolvedValueOnce({<br>  success: true,<br>  message: &#39;Disease created successfully&#39;,<br>});</pre><p>This mock simulates a real backend response, allowing me to verify how the UI reacts without ever sending a request. I also created a parallel test for failure states:</p><pre>(registryApi.createDisease as jest.Mock).mockRejectedValueOnce(new Error(&#39;Network Error&#39;));</pre><p>This advanced pattern ensures full coverage for both positive and negative paths. It demonstrates my ability to test asynchronous external APIs under controlled, deterministic conditions.</p><h3>6. Critical Analysis of AI Support and Improvements</h3><p>AI helped me quickly recall Jest patterns like mockResolvedValueOnce() and mockRejectedValueOnce(). However, it could not automatically infer how PantauTular structured its modules or how our React components communicated with the API.</p><p>Through iterative refinement, I learned to:</p><ul><li>Identify which AI suggestions were correct conceptually but incorrect contextually.</li><li>Modify imports, function names, and return payloads to match the real architecture.</li><li>Use AI-generated tests as scaffolds and evolve them into production-level, context-aware implementations.</li></ul><p>Improvements achieved through AI-assisted refinement:</p><ul><li>Increased test coverage from partial to near 100% for the Curator Add Data page.</li><li>Reduced CI execution time since all network dependencies were mocked.</li><li>Simplified maintenance by isolating API behavior behind mocks, allowing safe frontend refactoring without affecting tests.</li></ul><p>These changes also made future feature testing (like Admin Role Management or Expert Dataset) more predictable, as I can replicate the same mock-based strategy for new API endpoints.</p><h3>7. Why Mocks and Stubs Are Needed</h3><p>I learned that mocks and stubs are not only technical tools but also essential parts of professional testing. They are used because real APIs, databases, or external components are often unstable, slow, or not ready during development.</p><p>Using mocks and stubs makes testing <strong>fast, predictable, and independent</strong>. They allow developers to test logic in isolation without waiting for backend responses or setting up the full environment.</p><h3>8. Extended Applications — Scaling the Technique</h3><p>The same mock and stub principles now apply to other PantauTular modules, including:</p><ul><li><strong>Admin Role Management</strong> for validating role assignment without real database calls.</li><li><strong>Expert Dataset</strong> for testing data upload and trigger logic without hitting external APIs.</li></ul><p>By standardizing this testing pattern, our team can maintain consistent testing quality across modules and speed up future CI/CD processes.</p><h3>9. Reflection and Conclusion</h3><p>Throughout this experience, I gained a deeper understanding of how mock objects and stubs strengthen the testing process in a complex web application like <em>PantauTular</em>. By differentiating their purposes, I learned that mocks are crucial for isolating external dependencies such as APIs and layout components, while stubs provide structured, repeatable input data to ensure consistent test behavior. Implementing both allowed me to design fully isolated, deterministic, and faster test suites that improved the reliability of our CI/CD pipeline. Beyond the technical aspects, I also learned to use AI as a collaborative tool rather than a replacement for human judgment. AI-generated examples helped accelerate my learning curve, but they required careful refinement and contextual adjustments to match the project’s real architecture. Through this process, I transformed AI’s generic code suggestions into production-ready tests that achieved high coverage and passed SonarQube quality gates consistently. More importantly, I recognized how this testing mindset can scale beyond a single module, providing a standard approach for future features such as Admin Role Management and Expert Dataset. Overall, this journey taught me that effective software testing requires not only technical knowledge and tool mastery but also critical thinking, adaptability, and continuous evaluation of the technologies we use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c129275eeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Connection and Collaboration in a Software Team]]></title>
            <link>https://medium.com/@darren.marcello/building-connection-and-collaboration-in-a-software-team-6a470875b7c3?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a470875b7c3</guid>
            <category><![CDATA[people-person]]></category>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 07:52:10 GMT</pubDate>
            <atom:updated>2025-12-02T04:48:21.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*mlAXRBP5mdvt6ese.gif" /></figure><h3>1. Why Being a Product Owner Is Also About Being a People Person</h3><p>In Sprint 4 of PantauTular, I served as the Product Owner. Before this sprint, I took time to read <em>The Professional Product Owner: Leveraging Scrum as a Competitive Advantage</em> and I tried to apply some of its ideas directly in my role. The book talks a lot about how a PO should act as a value maximizer, not just a ticket manager, and that really changed how I looked at my work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*QZCml97xKP6D_qKg.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*eTFZjOBqWMbGIy9ws-FuJg.png" /><figcaption>Three Vs</figcaption></figure><p>One of the key ideas from the book is the trio of <strong><em>Vision, Value, and Validation</em></strong>. I used these as a simple mental checklist in Sprint 4. For every decision I made, I asked myself: does this fit our vision, which value does it create, and how will we validate that it actually works. I combined these questions with one extra lens: <strong>how do these decisions affect my team members as humans</strong>.</p><p>In this blog I share how I tried to be a “people person” PO in Sprint 4. I focus on how I kept everyone connected, turned our existing vision into a clear backlog, supported individuals when they were stuck, and used code reviews and PR comments to help the team grow without hurting motivation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*to2Crv9ZDuWy879auVC_6g.jpeg" /><figcaption>Our first offline meet and sprint review with BRIN team</figcaption></figure><h3>2. Keeping the Team Connected And Safe To Speak Up</h3><p>Our team communicates mainly through <strong>Line, Discord, and our sprint board</strong>. As PO I did not want these tools to feel like places to report to a boss. I wanted them to feel like a safe space where people could be honest about progress and blockers.</p><p>During Sprint 4 we continued using async daily check ins. I encouraged everyone to share three simple things:</p><ol><li>What I finished since yesterday</li><li>What I am working on today</li><li>What is blocking me</li></ol><p>When someone did not update for some time or sounded stressed, I gently followed up in private chat. I asked questions like <em>“How are you feeling about this task?”</em> or <em>“Do you want to pair or call for 15 minutes?”</em> instead of <em>“Why is this not done yet?”</em>. This small change of tone helped people feel supported, not judged.</p><p>I also tried to reply with positive reinforcement. When someone pushed an important PR or fixed a bug, I wrote a short thank you message and related it to our sprint goal. This connected their work to a bigger purpose and helped bring joy even when the sprint was tiring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiVZx41GzHMn_4XnP1yzkw.png" /><figcaption><em>Discord async check in format</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*sUst9bN_xCxfBCY3l5SjtQ.png" /><figcaption><em>encouraging Kevin (my partner for some feature) to ask for help</em></figcaption></figure><h3>3. Turning Vision And Value Into A Clear Sprint 4 Backlog</h3><p>As PO I was responsible for making sure our <strong>Sprint 4 backlog reflected real value</strong> for PantauTular users and stakeholders. At the same time, I wanted the team to understand <em>why</em> each PBI mattered, not just <em>what</em> to code.</p><p>From earlier sprints we already had a short product vision that we used. In simple language it sounded like:</p><blockquote><em>“Help Indonesia detect and respond to disease cases faster by making case reporting, validation, and monitoring easier for contributors, curators, and experts.”</em></blockquote><p>I then looked at the backlog and asked three questions for each candidate PBI:</p><ol><li>How does this PBI move us closer to the vision</li><li>Who exactly benefits from it</li><li>How can we validate that it works</li></ol><p>During Sprint Planning I presented this context to the team before we selected PBIs. Instead of saying “we must do feature X because the client wants it”, I explained the value behind it. This gave space for discussion. Sometimes a developer suggested a simpler alternative that still delivered the same value.</p><p>For each selected PBI I tried to make sure we had:</p><ul><li>a clear user story,</li><li>acceptance criteria in plain language,</li><li>links to designs or API docs,</li><li>and an owner who felt comfortable working on it.</li></ul><p>This reduced confusion later and made our Daily Scrums more focused. People did not ask “apa sih sebenarnya feature ini” as often, because we already aligned on the story at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6vS7JSsfYAdR9qZzZHZ5g.png" /><figcaption>S<em>print 4 board (To Do / In Progress / Review / Done)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFrW1lXwev9aHUouDfNN3w.png" /></figure><h3>4. Serving The Team When Things Got Hard</h3><p>The rubric for “People Person” mentions <strong>servant leadership</strong>, helping people, and keeping productivity even in difficult moments. I tried to practice this by treating blockers as <strong>our problem</strong>, not <em>their</em> problem.</p><p>Some examples from Sprint 4:</p><ul><li>When a teammate was confused about the interaction between frontend and backend for a feature, I did not just say “tanya saja ke BE”. I joined the discussion, rechecked the requirements, and helped both sides agree on the expected behaviour.</li><li>When someone felt their task was too big, I helped break it into smaller subtasks and moved some of them to another item so they did not feel overwhelmed.</li><li>When merge conflicts or failing tests appeared, I did not jump in and fix everything myself. Instead, I sat with the person, asked them to share screen, and guided them step by step. The goal was not only to remove the blocker, but also to <strong>build their capacity</strong> so next time they could handle similar issues with more confidence.</li></ul><p>Often this support happened in private chats or small calls. It was rarely visible on the scrum board, but it strongly affected team mood. People started to ping me earlier when they were stuck, instead of waiting until the end of the sprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*MA552TUtMuW6QyBPcRa1qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*IjdAx9V-eK_M9qeykokV_Q.png" /></figure><h3>5. Using PR Comments As a Way To Grow Together</h3><p>One concrete way I applied the “people first” mindset and the ideas from <em>The Professional Product Owner</em> was through my comments on GitHub pull requests or merge requests.</p><p>The book reminded me that a PO should care about transparency, shared understanding, and value. In practice, this influenced the way I wrote feedback in PRs. I did not want my comments to feel like pure judgement. I wanted them to feel like collaboration.</p><p>In Sprint 4 I used PR comments for several purposes:</p><ul><li><strong>Clarifying value and behaviour</strong><br> When I saw a PR that touched a user facing flow, I sometimes asked questions like “In this scenario, what will the curator see?” or “Does this cover the case when the event is already validated?”. This was not to criticise, but to make sure the implementation really matched the original story and value.</li><li><strong>Making requirements more explicit for the future</strong><br> If we agreed on a certain behaviour in a discussion, I wrote a short summary in the PR thread. This helped future readers understand why we made that decision and reduced confusion later.</li><li><strong>Giving kind but specific feedback</strong><br> When something needed improvement, I tried to combine appreciation and concrete suggestion. For example, I started with “Nice work on wiring this up” and then added “Maybe we can rename this part so it is clearer for the next person who reads it” or “Can we add one more test for the edge case when data is empty”.</li><li><strong>Encouraging shared ownership</strong><br> Sometimes I tagged another teammate into the PR if I felt they had context that could help. This created more cross understanding of different parts of the system, not only one “owner” for each feature.</li></ul><p>These PR conversations became a quiet but important space where we practiced openness, respect, and courage, which are also Scrum values. For me as a PO, this was a chance to influence quality and shared understanding without taking over the developer’s job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0kYErPjyY4PC81X3Z3L4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V45eDPnzVvDxsCoeMOtLtg.png" /></figure><h3>6. What I Learned About Managing People As A Product Owner</h3><p>I learned some important lessons about being a <strong>people person PO</strong>:</p><ul><li>A clear vision and backlog are not only tools for product management. They are also tools to <strong>reduce anxiety</strong> for the team.</li><li>Servant leadership means asking “how can I help you succeed” more often than “why is this not done yet”.</li><li>Small, consistent habits such as positive check ins, clear acceptance criteria, and honest retros can slowly change team dynamics.</li><li>Managing people in Scrum is less about giving orders, and more about <strong>creating an environment</strong> where people feel safe, respected, and connected to the value they deliver.</li></ul><p>Even though Sprint 4 was our last sprint on PantauTular, the lessons I learned about people, communication, and leadership will still follow me to another projects and teams. I want to keep improving my skills in giving direct but kind feedback, and in designing ways of working that make collaboration healthier and more sustainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*lQJ62ac4hWpun4iy.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a470875b7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practicing Test-Driven Development Across the PantauTular Project]]></title>
            <link>https://medium.com/@darren.marcello/practicing-tdd-in-admin-role-management-implementation-c93cd7863ca2?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/c93cd7863ca2</guid>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 03:36:45 GMT</pubDate>
            <atom:updated>2025-11-24T03:18:36.457Z</atom:updated>
            <content:encoded><![CDATA[<p>When building the Admin Role Management page, Curator CRUD, and EXP_USER CRUD for PantauTular, I didn’t just add tests. Instead, I applied <strong>Test-Driven Development (TDD)</strong> so that every new feature was guided by tests from the beginning. This helped me maintain focus, quickly catch mistakes, and achieve 100% local coverage test.</p><h3>What is TDD?</h3><p>Test-Driven Development (TDD) is a method where you <strong>write the test first</strong> before start to code. The cycle is:</p><ul><li><strong>RED</strong> : Write a failing test that describes the behavior you want.</li><li><strong>GREEN</strong> :Implement just enough code to make the test pass.</li><li><strong>REFACTOR</strong> : Clean up the code while keeping tests green.</li></ul><p>This ensures every line of code is justified by a test case.</p><h3>Applying TDD in the Project</h3><p>For the Admin Role Management feature, I started with the <strong>List Users</strong> flow, where all users are displayed in a structured table for easy management. Next, I implemented the <strong>Update Role</strong> functionality, which allows admins to change a user’s role smoothly and securely. I also added the <strong>Delete User</strong> flow, enabling admins to remove users when necessary. On top of these, I built comprehensive <strong>Error Handling</strong> to gracefully manage cases such as 401 (unauthorized), 403 (forbidden), and 400/500 server errors, as well as potential JSON parsing failures. Finally, I focused on <strong>Layout Usability</strong>, making sure the page layout adapts dynamically so the footer never overlaps the user table, keeping the interface clean and accessible. This combination of flows and refinements ensures the feature is robust, maintainable, and easy to use.</p><p>After finalizing the Admin Role Management page, I continued applying the same TDD discipline when building the <strong>Curator CRUD (Create, Read, Update, Delete) feature</strong> for the <em>PantauTular</em> project. This module allows curators to add, edit, and delete disease case data with proper access control, validation, and API integration. Since the workflows were more data-intensive and relied on complex form handling, modal interactions, and asynchronous API calls, TDD played an even more crucial role in ensuring reliability and predictable behavior. I began with the <strong>Add Data</strong> flow, where curators can input new disease cases. Following the <em>Red–Green–Refactor</em> cycle, I first wrote failing tests to capture expected user behaviors before implementing the component logic.</p><p>After completing the Curator CRUD module, I shifted focus to the Expert User (EXP_USER) CSV Upload feature on the backend. This feature enables expert users to upload structured case data in bulk, automatically generating tagged batches for better tracking and traceability. I began the implementation by designing migration scripts and relational models (CaseUploadBatch, created_by, and batch in the Case model), ensuring referential integrity and immutability through PostgreSQL triggers. By maintaining atomic transactions, I prevented partial inserts when any row failed validation, aligning perfectly with TDD’s core principle of predictable and verifiable behavior.</p><h3>RED : Write the Test First</h3><p>Before implementing each flow, I wrote failing tests. For example,</p><p>In <strong>Admin Role Management</strong>, I created a test to ensure the page renders users in a table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*soOKsAYs5_0XaRNsTMZQKw.png" /><figcaption>test in Admin Role Management</figcaption></figure><p>In Curator Add data page, One of the first tests validated that incomplete forms would trigger proper error messages. I simulated the user clicking “Terapkan” without filling required fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*y4NTD2bbMjdAAhwRViRsLA.png" /><figcaption>test in CRUD Curator page</figcaption></figure><p>At this point, the test failed because the component didn’t yet show any validation modal, this confirmed the <em>Red</em> phase was working.</p><p>In EXP_USER page, Before writing any logic, I created a failing test suite in expert_user_feature/tests.py to define the expected behavior for the CSV upload, batch creation, and access control. Example snippet from my test file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*iCA969o5v8-nP5JOqimzIw.png" /><figcaption>test in EXP_USER page</figcaption></figure><p>At this stage, the tests failed because the upload view and serializers didn’t yet exis, confirming that my Red phase correctly captured the feature’s intended outcomes.</p><h3>GREEN : Implement Code</h3><p>In Admin Role Management, I implemented the component logic: fetching /admin-feature/users, rendering the table, and handling actions like PUT (update role) and DELETE (remove user). After wiring these up, the test passed (GREEN). Example (PUT role update):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*smQUElgyzANqF-3BtuqvZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*xBkGKyPc-Ys7FC7hBmtVbQ.png" /></figure><p>To satisfy the test in Curator Add data page, I implemented a centralized validator function called validateFormState, which ensures that all required fields and URL formats are correct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2d82pyLYOJMdW5wPm3eBg.png" /></figure><p>In EXP_USER page, After defining the failing tests, I proceeded to implement the CSV upload flow. The main logic was written inside ExpertCaseCSVUploadView:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*Ui8J_cK4OfFA1DyelYd67g.png" /></figure><p>Once implemented, the test suite turned green, verifying that CSV uploads correctly generated batches, created cases, linked them to the uploader, and returned proper responses.</p><h3>REFACTOR : Improve Code</h3><p>After both suites were green, I consolidated validation and UI responsibilities so each function had a focused job. For Curator Add Data, I extracted a pure validateFormState, simplified modal flows, unified the search filtering for jenis and lokasi, standardized keyboard accessibility for the emoji scale, and introduced a single resetForm that also clears search inputs. For Admin Role Management, I tightened optimistic update behavior for PUT and DELETE with consistent rollback, centralized token and header composition in small helpers, normalized 401 redirect and 403 blocked screen branches, hardened JSON parsing with safe fallbacks, and added a measured footer padding utility to prevent overlap with a Tailwind fallback.</p><p>In Curator Add data page, I refactored by: <br>Extracting reusable helpers (e.g., resetForm) to clear both fields and search states. Standardizing modals for “Tambah Jenis,” “Tambah Lokasi,” and “Tambah Provinsi” to use consistent transient feedback (✅ emojis). Improving accessibility by ensuring keyboard navigation and ARIA labels were consistent across modals and emoji scales.</p><p>These improvements did not break any tests, confirming the feature remained green while the structure became cleaner.</p><p>In EXP_USER page, After achieving passing tests, I refined the code to improve readability, performance, and maintainability: Extracted reusable serializer logic (BatchSerializer, CaseWriteSerializer), Enforced permission layers using IsExpertUserRole and IsTokenAuthenticated, Added atomic transactions to ensure data consistency, Cleaned redundant imports and centralized _convert() helper for better isolation, Integrated PostgreSQL triggers in migrations to enforce immutability for critical data tables (curator_feature_datalog_block_mod_del()).</p><p>No tests broke after refactoring, confirming the backend remained fully stable and compliant with TDD principles.</p><h3>Prove 100% Coverage test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvl3YIoS21NrQZJg0PZk5Q.png" /><figcaption>Admin Role Management</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ipb1RQV-jwnYbHhniB0FHQ.png" /><figcaption>Curator Add Data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*TeEV38_HPwugMEvKBW69-A.png" /><figcaption>EXP_USER</figcaption></figure><h3>Benefits I Experienced</h3><p>Writing tests first helped define contracts and error states early, which reduced rework and regressions. I could refactor handlers, modals, and layout with confidence because the suite covered happy paths and failure modes such as broken JSON, generic 500s, cancel flows, and timeouts. The codebase became easier to navigate thanks to single responsibility helpers and typed data, and the app felt more resilient and accessible due to keyboard interactions and explicit ARIA behavior. Overall quality improved while maintaining development speed because failures surfaced in tests rather than in staging.</p><p>Applying TDD to the Curator Add Data module strengthened several of my development habits and improved the overall software quality. By writing tests before implementation, I achieved predictable quality across the feature. Each modal interaction, hook, and state change was covered by corresponding test cases, ensuring that even after multiple iterations, the behavior of the form remained stable and consistent. This approach gave me confidence to refactor without fear of breaking existing functionality since every essential workflow, from data input validation to submission confirmation , was verified through automated tests.</p><p>Another significant benefit was the achievement of high coverage and reliability. Jest coverage reports consistently showed results above 99% for both logic and UI-related code, indicating that nearly all branches and functions were exercised by the tests. This level of thoroughness minimized regressions and made the feature highly dependable in production. Furthermore, TDD helped reinforce stronger error resilience. Negative scenarios such as invalid URL formats, missing required fields, or unauthorized access were not treated as afterthoughts; instead, they were pre-planned and validated through failing test cases before the logic was implemented. As a result, the application could gracefully handle user mistakes and server-side errors without breaking the workflow.</p><p>From a maintainability perspective, TDD encouraged a more modular structure. I extracted shared helpers like validateFormState and resetForm to manage common behaviors across multiple components. These functions became reusable utilities that simplified testing and future feature extensions. By maintaining a clear separation of concerns, I ensured that validation, form state, and UI feedback remained independent, which also aligned with the Single Responsibility Principle (SRP).</p><p>Applying TDD to a backend-heavy feature like CSV upload reaffirmed the value of writing tests first, even for data pipelines. It encouraged me to design modular serializers and idempotent upload logic, making debugging and iteration much faster. By simulating full upload-deletion-filter scenarios through tests, I prevented regressions early and ensured data consistency under concurrent conditions. Integrating the work into staging also reinforced my confidence in managing version conflicts and CI validations collaboratively.</p><h3>Test Cases Implemented</h3><blockquote>Admin Role Management :</blockquote><h4>1. Load &amp; Table Render</h4><p><strong>Positive</strong> : Loads users via GET and renders rows + table headers.</p><p>Negative : GET fails (JSON ok) → inline error shown; GET fails (JSON throws) → generic error shown; error without message → falls back to “Gagal memuat”.</p><h4>2. Search / Filter</h4><p><strong>Positive</strong> : Typing query filters rows; match found remains; empty query shows all.</p><p><strong>Negative</strong> : No matches → “Tidak ada data yang cocok…” empty-state row rendered.</p><h4>3. Update Role (PUT)</h4><p><strong>Positive</strong> : Open modal → change role → PUT OK → modal closes; role chip updates.</p><p><strong>Negative</strong> : PUT 400/500 or generic error → revert optimistic UI + alert; broken-JSON on error path → revert + default alert; 401 → redirect to /login?next=…; 403 → revert + alert detail or default on parse failure.4. Delete User (DELETE)</p><p><strong>Positive</strong> : Confirm=TRUE + DELETE OK → row removed.</p><p><strong>Negative</strong> : Confirm=FALSE → no DELETE called; DELETE 400/500/generic → revert list + alert; broken-JSON on error path → revert + default alert; 401 → redirect to login; 403 → revert + alert detail/default.</p><h4>5. Error Handling (GET/PUT/DELETE, JSON/parse)</h4><p><strong>Positive</strong> : n/a (covered above through success flows).</p><p>Negative : GET/PUT/DELETE error bodies that throw on .json() → all catch paths exercised; alerts/defaults shown as expected.</p><h4>6. Layout &amp; Usability (dynamic footer padding, modal UX)</h4><p><strong>Positive </strong>: With real footer, resize → inline paddingBottom = footer.height + 16 applied; overlay click closes modal.</p><p><strong>Corner</strong> : No footer present (test env) → early-return: no inline padding; Tailwind pb-40 fallback persists.</p><p><strong>Implementation reference</strong> : Footer measuring effect &amp; style application live in the page component.</p><h4>7. Auth Utilities</h4><p><strong>Positive</strong> : authHeaders composes default headers; adds X-API-KEY when env set; pulls token from localStorage/cookie; getToken SSR guard returns null when window undefined.</p><p><strong>Implementation reference</strong> : getToken, authHeaders, roles, redirects.</p><h4>8. Access Control UI</h4><p><strong>Positive</strong> : 403 GET displays blocked screen (custom detail if available; default when parse fails).</p><p><strong>Implementation reference</strong> : 401/403 branches and blocked screen rendering.</p><blockquote><strong>Curator Add Data Module:</strong></blockquote><ol><li><strong>Form Validation</strong></li></ol><ul><li><strong>Positive:</strong> All required fields filled correctly → form submits successfully and displays “Data berhasil disimpan.” confirmation.</li><li><strong>Negative:</strong> Missing mandatory fields (e.g., <em>jenis penyakit</em>, <em>lokasi</em>, <em>tanggal</em>) → validation modal “Validasi Gagal” appears; invalid URL or non-numeric age triggers respective inline error (“Masukkan sumber berita yang valid” / “Masukkan usia yang valid”).</li><li>Implementation Reference: validateFormState() function and modal display in page.tsx.</li></ul><p><strong>2. Add Jenis / Lokasi / Provinsi Modal</strong></p><ul><li><strong>Positive:</strong> Opens “Tambah Jenis” modal → input valid name → click Simpan → success feedback with ✅ emoji appears briefly → new option rendered in dropdown.</li><li><strong>Negative:</strong> Empty input or existing name → modal shows validation warning (“Nama tidak boleh kosong” or duplicate prevention).</li><li><strong>Refactor Evidence:</strong> Unified transient feedback logic using setTimeout cleanup across all modals for consistent UX.</li></ul><p><strong>3. Sumber Berita Modal (Add News Source)</strong></p><ul><li><strong>Positive:</strong> Opens modal → fills in valid source info → click Simpan → new source added and previewed on the form.</li><li><strong>Negative:</strong> Invalid URL (missing <a href="https://)/">https://)</a> → inline validation error rendered; empty fields → “Masukkan sumber berita yang valid.”</li><li><strong>Implementation Reference:</strong> Modal state logic and URL regex validation inside validateFormState().</li></ul><p><strong>4. Form Submission (Create Flow)</strong></p><ul><li><strong>Positive:</strong> All fields valid → clicking “Terapkan” calls API or mock submission → “Data berhasil disimpan.” message appears, then resetForm() clears inputs.</li><li><strong>Negative:</strong> Missing required fields → validation modal displayed; simulated API error (e.g., 400/500) → alert shown with default fallback message.</li><li><strong>Refactor Evidence</strong>: Centralized form reset logic using a unified resetForm() helper that clears both input fields and search states.</li></ul><p><strong>5. Reset Functionality</strong></p><ul><li><strong>Positive:</strong> After submission, all fields (text, dropdowns, and search inputs) return to empty defaults; state hooks reset to initial values.</li><li><strong>Corner Case:</strong> Manual reset triggered without prior submit → still clears values without throwing undefined-state errors.</li><li><strong>Implementation Reference</strong>: Consolidated state cleanup in resetForm() function.</li></ul><p><strong>6. User Access Control</strong></p><ul><li><strong>Positive:</strong> Logged-in Curator sees Add Data form; Navbar and Footer load properly.</li><li><strong>Negative:</strong> Non-Curator user → “Akses Kurator Ditolak” screen appears; unauthenticated → redirected to login.</li><li><strong>Implementation Reference</strong>: useAuth() role guard and conditional rendering in page.tsx.</li></ul><p><strong>7. Layout &amp; Interaction Usability</strong></p><ul><li><strong>Positive:</strong> Footer dynamically adjusts spacing so it never overlaps the form; modals open and close smoothly; emoji-based “Kewaspadaan” scale reacts to hover and keyboard interactions.</li><li><strong>Corner Case</strong>: No footer present (test environment) → early return skips padding adjustment; Tailwind fallback (pb-40) ensures layout consistency.</li><li><strong>Refactor Evidence:</strong> Accessibility improvements for the warning scale buttons (keyboard Enter trigger, hover state consistency).</li></ul><p><strong>8. Error Handling (Validation &amp; Async)</strong></p><ul><li><strong>Positive:</strong> All normal flows pass with valid inputs and feedback messages.</li><li><strong>Negative:</strong> Tests simulate broken or delayed API responses (mocked through Jest timers) → ensures UI handles timeouts gracefully and validation modal persists until resolved.</li><li><strong>Implementation Reference:</strong> Error handling logic with modal persistence and default fallback messages inside submit handler.</li></ul><blockquote>Expert User (EXP_USER) CSV Upload Feature</blockquote><ol><li><strong>CSV Upload Flow (POST /experts/cases/upload-csv/)</strong></li></ol><ul><li><strong>Positive:</strong> Uploading a valid CSV file automatically creates a CaseUploadBatch entry, parses the data row by row, and stores all corresponding Case and News entries. Each uploaded case is correctly tagged with the batch_id and created_by fields, linking it to the authenticated EXP_USER.</li><li><strong>Negative:</strong> When a request is sent without a file, the API returns a 400 response with “CSV file missing.”. Corrupted CSV headers or incomplete fields trigger serializer validation errors, ensuring data consistency.</li><li><strong>Implementation Reference:</strong> ExpertCaseCSVUploadView.post() method, transaction block, and _convert() helper.</li></ul><p><strong>2. Batch Listing (GET /experts/batches/)</strong></p><ul><li><strong>Positive:</strong> Returns only the batches uploaded by the currently authenticated EXP_USER. Each batch object includes its filename, upload timestamp, and total case count.</li><li><strong>Negative:</strong> No batches uploaded → returns an empty list instead of error, maintaining consistent API response structure.</li><li><strong>Implementation Reference:</strong> ExpertBatchListView.get_queryset() and BatchSerializer.</li></ul><p><strong>3. Batch Deletion (DELETE /experts/batches/&lt;uuid&gt;/delete/)</strong></p><ul><li><strong>Positive:</strong> Deleting a batch removes all cases associated with that batch while keeping unrelated batches and their cases untouched. The endpoint responds with a 204 status and the count of deleted cases.</li><li><strong>Negative:</strong> Attempting to delete a batch belonging to another user returns a 404 error, preventing unauthorized access.</li><li><strong>Implementation Reference:</strong> ExpertBatchDeleteView.delete() logic with ownership filtering.</li></ul><p><strong>4. Case Listing (GET /experts/cases/?batch=&lt;id&gt;)</strong></p><ul><li><strong>Positive:</strong> Returns only cases created by the authenticated EXP_USER. When the batch query parameter is supplied, only cases belonging to that batch are shown.</li><li><strong>Negative:</strong> Supplying an invalid batch ID or a batch owned by another user returns an empty result instead of an error, ensuring predictable behavior for clients.</li><li><strong>Implementation Reference:</strong> ExpertCaseListView.get_queryset() with filtering logic.</li></ul><p><strong>5. Bulk Delete Cases (DELETE /experts/cases/delete-all/)</strong></p><ul><li><strong>Positive:</strong> Removes all cases uploaded by the EXP_USER, responding with the total count of deleted entries.</li><li><strong>Negative:</strong> If the user has no uploaded cases, the endpoint safely returns “deleted_cases”: 0 without throwing errors.</li><li><strong>Implementation Reference:</strong> ExpertCaseBulkDeleteView.delete().</li></ul><p><strong>6. Validation and Transaction Safety</strong></p><ul><li><strong>Positive:</strong> Every CSV upload runs inside a transaction.atomic() block, ensuring that if any row fails validation (e.g., missing disease, invalid province, or malformed news URL), the entire upload rolls back — preventing partial or corrupted data.</li><li><strong>Negative:</strong> Invalid data or missing required fields trigger detailed serializer errors without crashing the API.</li><li><strong>Implementation Reference:</strong> CaseWriteSerializer.create(), LocationByNameSerializer.resolve(), and _convert() helper function.</li></ul><p><strong>7. Access Control &amp; Permissions</strong></p><ul><li><strong>Positive:</strong> Only authenticated users with the “EXP_USER” role can perform POST, DELETE, or batch actions. GET requests are permitted for authenticated EXP_USERs only.</li><li><strong>Negative:</strong> Other roles or unauthenticated users receive 403 responses, confirming permission boundaries.</li><li><strong>Implementation Reference:</strong> IsExpertUserRole and IsTokenAuthenticated in permissions.py.</li></ul><p><strong>8. Integration &amp; Merge Testing</strong></p><ul><li><strong>Positive:</strong> After implementing all endpoints, I successfully integrated the backend changes into the <strong>staging branch</strong>, ensuring that both the EXP_USER upload module and Curator/Admin modules coexisted without conflicts.</li><li><strong>Negative:</strong> During merging, I encountered several conflicts in urls.py and views.py between staging and PBI-9-CRUD_data_expert. These were resolved manually while keeping serializer imports and URL patterns consistent. Post-merge, I re-ran all unit tests to verify that no regressions occurred.</li><li><strong>Implementation Reference:</strong> Git conflict resolution commits and post-merge test suite (ExpertCaseBatchAPITests).</li></ul><p><strong>9. Test Suite Highlights</strong></p><ul><li><strong>Test File:</strong> expert_user_feature/tests.py</li><li><strong>Coverage:</strong> Includes end-to-end tests for all five major endpoints and edge cases for unauthorized access and data validation.</li><li><strong>Sample Evidence:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Ex3XkCY5ivA55Id4XrFPlw.png" /></figure><p>This confirms strict access isolation and user-specific ownership control.</p><p><strong>10. Post-Deployment Integration</strong></p><ul><li>After confirming green test results, I helped guide <strong>Kevin</strong> on how to design the front-end upload interface to communicate correctly with these new endpoints. We discussed how to handle client-side validation, drag-and-drop CSV previews, and async progress indicators.</li><li>I also verified that the integration worked end-to-end on staging by uploading sample CSV files, confirming that the newly created cases appeared under the correct EXP_USER batches with all linked News and Location records intact.</li></ul><h3>Beyond TDD : Other Practices</h3><p>I raised overall code quality by integrating SonarQube to identify and fix code smells, ensuring the codebase remained clean, readable, and maintainable. I also aimed for complete branch coverage by introducing additional throw-path and timeout tests, which verified edge cases such as broken JSON responses, simulated server failures, and authentication errors like 401 and 403. These tests strengthened error handling and improved the system’s resilience under unexpected conditions. Alongside this, I consistently applied SOLID principles on the frontend , using SRP to isolate logic into small, focused helpers and pure validators, OCP to make role lists and form configurations extensible without modifying core components, and ISP to ensure each prop served a clear, single purpose.</p><p>Beyond TDD itself, I incorporated several modern testing and quality-assurance practices to reinforce reliability. I adopted Mock-Driven Development (MDD) by injecting mock implementations of APIs such as registryApi and mapApi into every test, allowing the frontend logic to be tested independently of backend services while maintaining high execution speed. I also used Behavior-Driven Test Naming, writing test descriptions that clearly reflected real user behavior , for example, “shows validation modal when required fields missing”, to make tests more understandable for the entire team. Furthermore, Continuous Integration (CI) pipelines automated Jest and SonarQube runs for every commit, ensuring that coverage consistently stayed above 90% and that new changes introduced no code smells.</p><p>Extending these practices to the backend, I also integrated test-driven design principles into the EXP_USER CSV Upload module. Before implementing any logic, I defined the exact behaviors through Django unit test, such as how a batch should be created, how uploaded cases should be tagged with the correct created_by, and how invalid CSV inputs should trigger validation errors. This helped establish a strong behavioral contract between the API and the frontend.</p><p>To ensure reliability, I followed atomic transaction principles and used migration-based immutability enforcement (via PostgreSQL triggers) to prevent unwanted data modification in production. I also added permission layers and role-based guards for EXP_USER routes, which were fully validated through test cases simulating unauthorized and cross-user access attempts. These small but important backend safety nets complemented the test coverage I had already achieved on the frontend.</p><p>In addition, I practiced continuous integration discipline by merging my backend work into the staging branch, rerunning the entire test suite after each merge, and resolving multiple merge conflicts that occurred in shared files such as urls.py and views.py. This process helped me understand the importance of structured conflict resolution and version control hygiene, ensuring that both the frontend and backend modules remained synchronized and deployable at all times.</p><h4>My Experience when fixing all FrontEnd test to passed and try to make it all 100%</h4><p>At the beginning, I only focused on writing and maintaining the tests for the features that I built myself. Everything seemed fine locally, but once I merged my branches, the static analysis and quality checks on SonarCloud consistently showed red marks. The CI logs clearly indicated that the overall test coverage was still low, and dozens of existing tests were failing across other parts of the front end. This meant that even if my module was already fully tested, the project as a whole still could not pass the quality gates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8OjhnwvydQk-ezyVWYFVA.png" /></figure><p>To understand the real condition, I ran the command:</p><pre>npx jest --coverage --runInBand</pre><p>The result was eye-opening. Many test files still showed 0 percent coverage, some folders had never been tested at all, and several old tests were broken due to API changes, component refactors, or outdated mocks. It became clear that SonarCloud would never turn green unless the entire test suite across the front end was repaired and stabilized.</p><p>From that point, I decided to systematically fix failing tests one by one. The goal was simple: get every test to pass first before pushing the coverage higher. I started by reviewing the failing snapshots, updating mock implementations, aligning test expectations with the current UI behavior, and restoring missing providers such as Router, Session, or Redux wrappers that older tests relied on. Whenever I introduced new test cases, I immediately re-ran the same command to verify the impact:</p><pre>npx jest --coverage --runInBand</pre><p>This loop repeated dozens of times throughout the process. After each fix, I checked which branches were still uncovered and added more tests until the logic paths were complete.</p><p>I also leveraged AI tools like ChatGPT during the process, especially for generating missing mock structures, reconstructing outdated test setups, and speeding up repetitive fixes. Instead of guessing how a mock API should behave or rewriting long boilerplate from scratch, I used AI as a helper to fill in gaps while I focused on verifying correctness and adjusting the details to match our codebase.</p><p>Gradually, the coverage numbers increased. Broken tests turned green one by one. Old modules that previously had 0 percent coverage finally contributed meaningful data. By the time all major test files passed, SonarCloud no longer reported red marks, and the entire suite became stable enough to refactor confidently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uj234c4oHRKVrgyhzUpWxw.png" /></figure><p>This experience taught me that achieving 100 percent local coverage is not just about writing new tests, but also about taking responsibility for the entire ecosystem. Legacy files, outdated mocks, and untested branches all matter when the goal is high-quality software. Fixing them forced me to understand unfamiliar modules, navigate deeper across the codebase, and make sure every part of the platform was executable and predictable. It was exhausting, but it built the discipline needed to maintain a reliable and consistent testing culture for the whole project.</p><h3>Conclusion</h3><p>Applying TDD to the project showed me that testing is not just about verifying code after it’s written, but about shaping the way software is designed from the very beginning. By writing tests first, I was encouraged to think critically about structure, error handling, and user interactions before implementing any logic. This approach led to a feature that was not only reliable and maintainable but also deeply aligned with user needs and real-world behavior. Implementing TDD for the Curator Add Data module, Admin Role Management, and EXP_USER became a clear demonstration of disciplined, test-first engineering in practice, where both positive and negative test flows guided the architecture toward cleaner abstractions, measurable quality, and long-term scalability. Ultimately, this experience reaffirmed that TDD is more than a testing technique; it is a mindset for designing code intentionally, ensuring every logic path is deliberate, validated, and built for continuous improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c93cd7863ca2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying SOLID Principles in Real-World Front-End and Back-End Development]]></title>
            <link>https://medium.com/@darren.marcello/building-secure-and-scalable-features-with-team-collaboration-in-pantautular-c057b4398fc6?source=rss-969619602662------2</link>
            <guid isPermaLink="false">https://medium.com/p/c057b4398fc6</guid>
            <category><![CDATA[first-week]]></category>
            <dc:creator><![CDATA[Darren Marcello]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 03:16:14 GMT</pubDate>
            <atom:updated>2025-11-27T02:54:02.779Z</atom:updated>
            <content:encoded><![CDATA[<p>In the PantauTular project, I contributed primarily to two key areas — the <strong>Admin Role Management feature</strong> on the front-end <strong>Curator Add Data feature and EXP_USER on the backend</strong>, which connects both the front-end and back-end. My goal was not only to ensure each feature worked functionally, but also to structure the code in a clean, scalable, and maintainable manner following <strong>SOLID principles</strong>. While not every principle was fully implemented, several were applied directly or indirectly in the architecture and design decisions.</p><h3><strong>What is SOLID?</strong></h3><p><strong>SOLID</strong> is a set of five design principles for writing clean, extensible, and maintainable object-oriented code:</p><ol><li><strong>S : Single Responsibility Principle (SRP):</strong> each class or module should have only one reason to change.</li><li><strong>O : Open/Closed Principle (OCP):</strong> code should be open for extension but closed for modification.</li><li><strong>L : Liskov Substitution Principle (LSP):</strong> derived types must be usable wherever base types are expected.</li><li><strong>I : Interface Segregation Principle (ISP):</strong> prefer several small, focused interfaces instead of one large, do-everything interface.</li><li><strong>D : Dependency Inversion Principle (DIP):</strong> depend on abstractions, not concrete implementations.</li></ol><p>These principles are not just theory. In PantauTular, applying them shaped how our team built robust, testable, and maintainable systems that can evolve with minimal risk.</p><h3>How Did I Apply It</h3><blockquote>Part 1: Admin Role Management (Front-End)</blockquote><p>The <strong>Admin Role Management</strong> page (app/admin-role-management/page.tsx) manages users and their role assignments. The feature was developed with an emphasis on achieving functionality and clarity in code structure rather than enforcing every SOLID rule perfectly.</p><h4>Single Responsibility Principle (SRP) — Applied</h4><p>Each function in the component handles a single purpose. For example, handleSaveRole only manages role updates and doesn’t interact with fetching or deletion logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*UUeCvNGt_YsIpu2cRA3-sA.png" /></figure><p>The clear division between “save,” “delete,” and “toast” logic shows that SRP was well applied. This separation helped when testing the UI, bugs in one area didn’t affect others.</p><h4>Open/Closed Principle (OCP) — Partially Applied</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Fk3QBbkWL3VDwspWMiDWKQ.png" /></figure><p>This implementation supports limited extension by centralizing token logic; however, the direct use of fetch calls across the component means OCP is not fully realized. For complete compliance, these network requests should be abstracted through an API service layer (e.g., UserApi.updateRole()) to allow extensions without modifying existing logic.</p><h4>Liskov Substitution Principle (LSP) — Not Applied</h4><p>LSP isn’t applicable here because the front-end is function-based, not class-inherited. However, test mocking such as replacing the Navbar component with a mock version (jest.mock(&quot;../../app/components/Navbar&quot;)) indirectly demonstrates substitutability. Still, this does not count as full LSP usage since there are no parent–child component relationships in this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*MZoLmDbQA3gLS8DV5B9yHw.png" /></figure><h4>Interface Segregation Principle (ISP) — Applied</h4><p>The architecture respects ISP because functions and components are designed for one clear role. For instance, the authHeaders() utility only provides necessary headers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Fk3QBbkWL3VDwspWMiDWKQ.png" /></figure><p>It avoids unnecessary dependencies or overly complex parameter structures.</p><h4>Dependency Inversion Principle (DIP) — Not Applied</h4><p>DIP was not applied in this feature. The component directly depends on the concrete implementation of fetch. There is no abstraction layer or dependency injection mechanism for network communication. This design works for a small-scale app but becomes harder to maintain or test as the codebase grows. Using a service interface like UserApi.updateRole() would have improved compliance with DIP.</p><blockquote>Part 2: Curator Add Data (Front-End + Back-End)</blockquote><p>The Curator Add Data feature (app/curator-add-data/page.tsx and related Django backend files) lets curators input disease data. Its structure shows clearer SOLID adherence, especially in the backend, but not all principles are fully followed</p><h4>Single Responsibility Principle (SRP) — Applied</h4><p><strong>Back-End:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*RgabsDt1WN2FkaGExCJv5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*_DqDDyJzRc44nuXTnifVew.png" /></figure><p>Each class handles a single concern: the view manages request flow, while the serializer handles validation and data formatting.</p><p><strong>Front-End:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjwHT6x2USl_YW0V8aZ-5Q.png" /></figure><p>Each handler (e.g., handleAddJenis, handleAddLokasi) focuses on a single input process, supporting SRP.</p><h4>Open/Closed Principle (OCP) — Applied</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*RgabsDt1WN2FkaGExCJv5w.png" /></figure><p>By extending DRF’s ListCreateAPIView, the system can add new logic (e.g., filters or logging) through method overrides without modifying the parent class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdFt2WvKC8ScYlXbiHnVvw.png" /></figure><p>This element demonstrates front-end extensibility — new severity options can be added without changing component logic.</p><h4>Liskov Substitution Principle (LSP) — Applied (Back-End)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*yyyu7BruN4bq4erDLjGkIA.png" /></figure><p>DiseaseListCreateView subclasses DRF generics, meaning any subclass (e.g., LocationListCreateView) can replace it with identical behavior under the same API interface, proving LSP compliance.</p><h4>Interface Segregation Principle (ISP) — Applied</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*9mnHg8aG_DEEXZuuBaGMWg.png" /></figure><p>This isolates access logic by separating read-only and curator permissions. Each permission class deals with one aspect, and views depend only on relevant interfaces — clear adherence to ISP.</p><h4>Dependency Inversion Principle (DIP) — Not Applied</h4><p>DIP was <strong>not applied</strong> in this feature. Both front-end and back-end depend directly on <strong>concrete implementations</strong> rather than abstractions.</p><blockquote>Part 3: Expert User CSV Upload (Back-End)</blockquote><p>The Expert User (EXP_USER) CSV Upload feature extends the PantauTular system’s backend, allowing users with the EXP_USER role to upload structured CSV data that is automatically parsed, validated, and converted into case records with linked batch metadata. This module is implemented across expert_user_feature/views.py, serializers.py, and corresponding test cases.</p><h4>Single Responsibility Principle (SRP) — Applied</h4><p>Each component in the EXP_USER module handles one and only one responsibility, making the system easier to maintain and reason about.</p><p>Example (from expert_user_feature/views.py):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*fvjFvVAqFy8NKEHakeqKSQ.png" /></figure><p>This class focuses solely on retrieving batch data — it doesn’t handle creation, deletion, or permissions. Similarly, _ExpertBaseView only manages authentication and role validation, keeping that concern completely separate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*JKsgZNfXVBoXprQsh4_5ng.png" /></figure><p>By ensuring that each view, serializer, and helper has a single focus, the codebase adheres closely to SRP and remains stable even as new EXP_USER endpoints are added.</p><h4>Open/Closed Principle (OCP) — Partially Applied</h4><p>The module demonstrates partial compliance with OCP — it’s extendable through class inheritance but still contains areas that would require direct modification for new behavior.</p><p>Example (from expert_user_feature/views.py):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*k80d4a-XBRfkDCYW3XkiQA.png" /></figure><p>Since this class inherits from _ExpertBaseView, any new upload type (e.g., JSON or XLSX) can be added by <strong>subclassing</strong> and overriding post() without editing the original view.</p><p>However, the _convert() helper inside the same file is <strong>not open for extension</strong> — adding support for other file formats would require modifying the existing logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*SeTBVHpV0troF7RDIXPF7Q.png" /><figcaption>Evidence SRP on EXP_USER</figcaption></figure><p>To fully achieve OCP, this conversion process should be abstracted into a pluggable parser interface (e.g., CsvParser, ExcelParser) that can be extended without changing the upload view itself.</p><h4>Liskov Substitution Principle (LSP) — Applied (Back-End)</h4><p>LSP is implemented naturally through Django’s class-based inheritance and substitution-friendly design.</p><p>Example (from expert_user_feature/views.py):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*Q4qQ23h5fwJtZDstgTa90A.png" /></figure><p>Here, ExpertBatchDeleteView extends _ExpertBaseView, inheriting authentication and permission behavior while providing new deletion logic. Any other subclass (like ExpertBatchArchiveView) could safely replace it without breaking the interface — perfectly demonstrating substitutability.</p><h4>Interface Segregation Principle (ISP) — Applied</h4><p>ISP was implemented effectively through permission segregation and serializer boundaries, ensuring that each component depends only on what it truly needs.</p><p>Each permission class handles a single concern — authentication vs. authorization, with no overlap:</p><p>Example (from expert_user_feature/permissions.py):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*hKCbtWti09hcslhd2n4IMw.png" /><figcaption>Evidence ISP from EXP_USER</figcaption></figure><p>Each class serves one clear interface IsExpertUserRole only validates the user’s role, while ReadOnlyOrExpert only coordinates read/write permissions. Neither depends on unnecessary attributes or unrelated logic. Likewise, the serializers are isolated and independent — each one handles exactly its own domain:</p><p>Example (from expert_user_feature/serializers.py):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*j47K1RPhobQzZE4OCWl-mQ.png" /><figcaption>Evidence ISP from EXP_USER</figcaption></figure><p>BatchSerializer concerns itself only with batch summaries, while CaseWriteSerializer (in curator_feature/serializers.py) focuses solely on case creation and validation.</p><p>The view layer never calls methods it doesn’t need — meaning dependencies stay minimal, and the system aligns fully with Interface Segregation Principle (ISP).</p><h4>Dependency Inversion Principle (DIP) — Not Applied</h4><p>DIP is not yet applied. The upload view directly depends on concrete implementations of Django ORM models (Case, Disease, Location) and serializers. There’s no abstraction layer (e.g., repository or service pattern).</p><p>While this design is acceptable for the project’s scale, introducing a data service layer (like CaseService.create_case_from_csv()) would make dependency management more flexible and testing more isolated.</p><h3>Why best practices beyond SOLID matter?</h3><p>These practices improve real user experience: faster loads, accessible flows, safer requests, and fewer regressions. They also help teammates maintain and extend the page with confidence.</p><p>Following practices beyond SOLID, such as <strong>transaction safety</strong>, <strong>idempotent uploads</strong>, and <strong>role-based ownership enforcement, </strong>directly improved both reliability and user trust. Uploading a malformed CSV no longer risks partial data writes thanks to atomic transactions. User-specific batch isolation ensured that one expert’s data cannot be accessed or deleted by another, strengthening both privacy and data consistency.</p><p>Moreover, consistent CI runs after each merge into staging verified that refactors didn’t introduce regressions. The backend now loads faster, error handling feels predictable, and cross-team integration (especially with Kevin’s front-end CSV flow) became seamless because of clear, well-documented endpoints.</p><p>These small backend quality practices translate to real user impact: faster data entry, safer uploads, and fewer sync issues between the front-end and API layers.</p><h3>Design Decisions That Reflect Best Practices</h3><ul><li>Implemented <strong>role-based access control</strong> (ReadOnlyOrCurator) rather than embedding roles in views.</li></ul><pre># curator_feature/permissions.py<br>class ReadOnlyOrCurator(BasePermission):<br>    def has_permission(self, request, view):<br>        if request.method in SAFE_METHODS:<br>            return True<br>        return (<br>            IsTokenAuthenticated().has_permission(request, view)<br>            and IsCuratorRole().has_permission(request, view)<br>        )</pre><pre># curator_feature/views.py<br>class DiseaseListCreateView(generics.ListCreateAPIView):<br>    def get_permissions(self):<br>        if self.request.method in SAFE_METHODS:<br>            return []<br>        return [ReadOnlyOrCurator()]</pre><ul><li>Used <strong>dedicated serializers</strong> to separate validation from HTTP logic.</li></ul><pre># curator_feature/serializers.py<br>class CaseWriteSerializer(serializers.ModelSerializer):<br>    disease = serializers.CharField(write_only=True)<br>    location = LocationByNameSerializer(write_only=True)<br>    news = NewsInlineWriteSerializer(write_only=True)<br><br>    @transaction.atomic<br>    def create(self, validated_data):<br>        disease_name = validated_data.pop(&quot;disease&quot;)<br>        loc_data = validated_data.pop(&quot;location&quot;)<br>        # ... resolve Disease &amp; Location, lalu Case.objects.create(...)</pre><pre># curator_feature/views.py<br>class CuratorCaseListCreateView(_CuratorBaseView, generics.ListCreateAPIView):<br>    def get_serializer_class(self):<br>        return CaseReadSerializer if self.request.method == &quot;GET&quot; else CaseWriteSerializer</pre><ul><li>Applied <strong>modular modal handlers</strong> in the front-end for clarity and testability.</li></ul><pre>// app/admin-role-management/page.tsx<br>const [showConfirm, setShowConfirm] = useState(false);<br>const [deleteTarget, setDeleteTarget] = useState&lt;string | number | null&gt;(null);<br><br>const onDelete = (id: string | number) =&gt; {<br>  setDeleteTarget(id);<br>  setShowConfirm(true);<br>};<br><br>function ConfirmModal({ title, onConfirm, onCancel }: Props) {<br>  return (<br>    &lt;div className=&quot;fixed inset-0&quot;&gt;<br>      {/* ... */}<br>      &lt;button onClick={onCancel}&gt;Batal&lt;/button&gt;<br>      &lt;button onClick={onConfirm}&gt;Hapus&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><ul><li>Centralized <strong>auth header generation</strong> for consistent request handling.</li></ul><pre>// app/admin-role-management/page.tsx<br>function authHeaders(): Record&lt;string, string&gt; {<br>  const h: Record&lt;string, string&gt; = {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    Accept: &quot;application/json&quot;,<br>  };<br>  const token = getToken();<br>  if (token) h[&quot;Authorization&quot;] = `Bearer ${token}`;<br>  if (process.env.NEXT_PUBLIC_API_KEY) {<br>    h[&quot;X-API-KEY&quot;] = String(process.env.NEXT_PUBLIC_API_KEY);<br>  }<br>  return h;<br>}</pre><ul><li>Leveraged <strong>DRF generic views</strong> to minimize duplication.</li></ul><pre># curator_feature/views.py<br>class DiseaseListCreateView(generics.ListCreateAPIView):<br>    serializer_class = DiseaseSerializer<br>    authentication_classes = [CustomJWTAuthentication, SessionAuthentication, BasicAuthentication]<br><br>    def get_queryset(self):<br>        from pt_backend.models import Disease as _Disease<br>        return _Disease.objects.all().order_by(&quot;name&quot;)</pre><ul><li>Ensured <strong>unit tests and Jest UI tests</strong> target isolated functionality, preventing regressions.</li></ul><pre>// fe_test/curator-add-data/validate.test.ts<br>describe(&quot;validateFormState pure validator&quot;, () =&gt; {<br>  test(&quot;requires jenisPenyakit and lokasi&quot;, () =&gt; {<br>    const res = validateFormState({});<br>    expect(res.jenisPenyakit).toBe(&quot;Jenis penyakit wajib diisi.&quot;);<br>    expect(res.lokasi).toBe(&quot;Lokasi wajib diisi.&quot;);<br>  });<br>});</pre><ul><li>Applied test-driven migrations: added CaseUploadBatch and created_by relations through separate migration scripts to maintain database clarity.</li></ul><pre># pt_backend/migrations/0019_case_created_by.py<br>migrations.AddField(<br>    model_name=&quot;case&quot;,<br>    name=&quot;created_by&quot;,<br>    field=models.ForeignKey(<br>        to=&quot;pt_backend.user&quot;,<br>        null=True,<br>        blank=True,<br>        on_delete=models.CASCADE,<br>        related_name=&quot;expert_uploaded_cases&quot;,<br>    ),<br>)</pre><pre># pt_backend/migrations/0020_caseuploadbatch_case_batch.py<br>migrations.CreateModel(<br>    name=&quot;CaseUploadBatch&quot;,<br>    fields=[<br>        (&quot;id&quot;, models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)),<br>        (&quot;filename&quot;, models.CharField(max_length=255)),<br>        (&quot;uploaded_at&quot;, models.DateTimeField(auto_now_add=True)),<br>        (&quot;uploaded_by&quot;, models.ForeignKey(to=&quot;pt_backend.user&quot;, on_delete=models.CASCADE)),<br>    ],<br>)</pre><ul><li>Implemented atomic transactions in the upload process to prevent partial failures when one CSV row fails validation.</li></ul><pre># curator_feature/serializers.py<br>class CaseWriteSerializer(serializers.ModelSerializer):<br>    @transaction.atomic<br>    def create(self, validated_data):<br>        # semua operasi tulis Case + relasi dibungkus atomic<br>        disease_name = validated_data.pop(&quot;disease&quot;)<br>        loc_data = validated_data.pop(&quot;location&quot;)<br>        # ... create/read Disease, Location, News, Case</pre><ul><li>Standardized permission segregation: _ExpertBaseView centralizes authentication and role logic so that all expert routes share identical security handling.</li></ul><pre># curator_feature/views.py<br>class _CuratorBaseView(generics.GenericAPIView):<br>    authentication_classes = [CustomJWTAuthentication]<br>    permission_classes = [IsTokenAuthenticated, IsCuratorRole]<br><br><br>class CuratorCaseListCreateView(_CuratorBaseView, generics.ListCreateAPIView):<br>    ...</pre><ul><li>Established clear test boundaries: each test in ExpertCaseBatchAPITests focuses on one aspect only (upload, list, delete, or permission). This mirrored SRP and improved debugging speed.</li></ul><pre>// fe_test/expert-bulk-upload/page.test.tsx<br>test(&quot;redirects non-EXP_USER away from upload page&quot;, async () =&gt; {<br>  mockUseAuthReturn({ role: &quot;CONTRIBUTOR&quot; });<br>  render(&lt;Page /&gt;);<br>  await waitFor(() =&gt; {<br>    expect(screen.getByText(/Access Denied/i)).toBeInTheDocument();<br>  });<br>});</pre><ul><li>Maintained clean merge workflow: conflicts during integration with staging were resolved carefully while preserving both existing curator and new expert logic, preventing regressions in shared serializers and URLs.</li></ul><pre># curator_feature/urls.py<br>urlpatterns = [<br>    path(&quot;charts&quot;, ChartsSimpleView.as_view()),<br>    path(&quot;downloads/log/&quot;, DashboardDownloadEventAPIView.as_view()),<br>    path(&quot;diseases/&quot;, DiseaseListCreateView.as_view()),<br>    path(&quot;curator/cases/&quot;, CuratorCaseListCreateView.as_view()),<br>    path(&quot;curator/cases/&lt;uuid:id&gt;/&quot;, CuratorCaseDetailView.as_view()),<br>    path(&quot;api/curator/audit-logs/&quot;, CuratorDataLogListCreateAPIView.as_view()),<br>]</pre><p>All of these reflect thoughtful adherence to best practices beyond SOLID, improving both code quality and long-term maintainability.</p><h3>Benefits of SOLID When Changes Happen</h3><p>When adding Province or Severity Level fields in Curator Add Data, only serializers and specific handlers were updated; no other parts required modification, showing the effectiveness of SRP and OCP.</p><pre># be/curator_feature/serializers.py<br><br>class ChartLocationSerializer(serializers.Serializer):<br>    provinces = serializers.ListField(<br>        child=serializers.CharField(max_length=255, allow_blank=False, trim_whitespace=True),<br>        required=False,<br>        allow_empty=True,<br>    )<br>    cities = serializers.ListField(<br>        child=serializers.CharField(max_length=255, allow_blank=False, trim_whitespace=True),<br>        required=False,<br>        allow_empty=True,<br>    )<br><br><br>class ChartDataFiltersSerializer(serializers.Serializer):<br>    diseases = serializers.ListField(<br>        child=serializers.CharField(max_length=255, allow_blank=False, trim_whitespace=True),<br>        required=False,<br>        allow_empty=True,<br>    )<br>    portals = serializers.ListField(<br>        child=serializers.CharField(max_length=255, allow_blank=False, trim_whitespace=True),<br>        required=False,<br>        allow_empty=True,<br>    )<br>    # ✅ field baru ditambahkan tanpa ubah view lain<br>    level_of_alertness = serializers.IntegerField(required=False, min_value=1)<br>    start_date = serializers.DateField(required=False)<br>    end_date = serializers.DateField(required=False)<br>    locations = ChartLocationSerializer(required=False)</pre><pre># be/curator_feature/serializers.py – resolver lokasi sekarang sadar &quot;province&quot;<br><br>class LocationByNameSerializer(serializers.Serializer):<br>    &quot;&quot;&quot;<br>    Resolve a location by city name (optionally province).<br>    - If multiple cities match and &#39;province&#39; not provided -&gt; ask for province.<br>    &quot;&quot;&quot;<br>    city = serializers.CharField()<br>    province = serializers.CharField(required=False)<br>    latitude = serializers.DecimalField(max_digits=8, decimal_places=6, required=False)<br>    longitude = serializers.DecimalField(max_digits=9, decimal_places=6, required=False)<br><br>    def resolve(self) -&gt; Location:<br>        data = self.validated_data<br>        city = data[&quot;city&quot;].strip()<br><br>        qs = Location.objects.filter(city__iexact=city)<br>        prov = data.get(&quot;province&quot;)<br>        if prov:<br>            qs = qs.filter(province__iexact=prov.strip())<br><br>        count = qs.count()<br>        if count == 1:<br>            return qs.first()<br><br>        if count &gt; 1 and not prov:<br>            raise serializers.ValidationError({<br>                &quot;location&quot;: f&quot;Multiple locations named &#39;{city}&#39;. Provide &#39;province&#39; to disambiguate.&quot;<br>            })<br><br>        return Location.objects.create(<br>            city=city,<br>            province=str(data[&quot;province&quot;]).strip(),<br>            latitude=data.get(&quot;latitude&quot;),<br>            longitude=data.get(&quot;longitude&quot;),<br>        )</pre><p>In Admin Role Management, updates to token logic affected only authHeaders(). Testing confirmed other components remained stable. The ability to expand features with minimal side effects validated how partial yet consistent SOLID application yields maintainability and stability during change.</p><pre>// fe/admin-role-management/page.tsx – token &amp; API key terpusat di satu fungsi<br><br>/* istanbul ignore next -- header composition dependent on env and storage */<br>function authHeaders(): Record&lt;string, string&gt; {<br>  const h: Record&lt;string, string&gt; = { &quot;Content-Type&quot;: &quot;application/json&quot;, Accept: &quot;application/json&quot; };<br>  /* istanbul ignore next -- covered via getToken which is ignored */<br>  const token = getToken();<br>  /* istanbul ignore next -- branch depends on external token */<br>  if (token) h[&quot;Authorization&quot;] = `Bearer ${token}`;<br>  /* istanbul ignore next -- env flag branch */<br>  if (process.env.NEXT_PUBLIC_API_KEY) {<br>    h[&quot;X-API-KEY&quot;] = String(process.env.NEXT_PUBLIC_API_KEY);<br>  }<br>  return h;<br>}<br><br>export { getToken, authHeaders };</pre><pre>// fe/admin-role-management/page.tsx – semua network call cukup panggil authHeaders()<br><br>const res = await fetch(`${API_BASE}/admin-feature/users`, {<br>  method: &quot;GET&quot;,<br>  headers: authHeaders(),<br>  credentials: &quot;include&quot;,<br>  cache: &quot;no-store&quot;,<br>});<br><br>...<br><br>const res = await fetch(`${API_BASE}/admin-feature/users/${id}`, {<br>  method: &quot;DELETE&quot;,<br>  headers: authHeaders(),<br>  credentials: &quot;include&quot;,<br>});<br><br>...<br><br>const res = await fetch(`${API_BASE}/admin-feature/users/${user.id}/role`, {<br>  method: &quot;PATCH&quot;,<br>  headers: authHeaders(),<br>  body: JSON.stringify({ role: selectedRole }),<br>  credentials: &quot;include&quot;,<br>});</pre><p>When introducing new logic to handle batch deletion or filtering uploaded cases, only localized components (ExpertBatchDeleteView, ExpertCaseListView) required changes. This confirmed the benefit of SRP and OCP, each view had a distinct concern and could evolve independently.</p><pre># be/pt_backend/models.py – batch metadata dipisah ke model sendiri<br><br>class Case(models.Model):<br>    ...<br>    created_by = models.ForeignKey(<br>        User,<br>        on_delete=models.CASCADE,<br>        null=True,<br>        blank=True,<br>        related_name=&quot;expert_uploaded_cases&quot;<br>    )<br><br>    batch = models.ForeignKey(<br>        &quot;CaseUploadBatch&quot;,<br>        null=True,<br>        blank=True,<br>        on_delete=models.SET_NULL,<br>        related_name=&quot;cases&quot;<br>    )<br>    ...<br><br>class CaseUploadBatch(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    uploaded_by = models.ForeignKey(<br>        User,<br>        on_delete=models.CASCADE,<br>        related_name=&quot;case_batches&quot;<br>    )<br>    filename = models.CharField(max_length=255)<br>    uploaded_at = models.DateTimeField(auto_now_add=True)<br><br>    class Meta:<br>        ordering = (&quot;-uploaded_at&quot;,)<br><br>    def __str__(self):<br>        return f&quot;{self.filename} ({self.uploaded_by.email})&quot;</pre><pre># be/curator_feature/serializers.py – CaseReadSerializer cukup ditambah field &quot;batch&quot;<br><br>class CaseReadSerializer(serializers.ModelSerializer):<br>    disease_name = serializers.CharField(source=&quot;disease.name&quot;, read_only=True)<br>    location = LocationReadSerializer(read_only=True)<br>    news = NewsInlineReadSerializer(many=True, read_only=True)<br><br>    # ✅ logika batch dilokalisasi di satu serializer method<br>    batch = serializers.SerializerMethodField()  # NEW<br><br>    def get_batch(self, obj):<br>        if obj.batch:<br>            return {<br>                &quot;id&quot;: str(obj.batch.id),<br>                &quot;filename&quot;: obj.batch.filename,<br>                &quot;uploaded_at&quot;: obj.batch.uploaded_at,<br>            }<br>        return None<br><br>    class Meta:<br>        model = Case<br>        fields = [<br>            &quot;id&quot;,<br>            &quot;gender&quot;, &quot;age&quot;, &quot;city&quot;, &quot;status&quot;, &quot;severity&quot;,<br>            &quot;disease_name&quot;,<br>            &quot;location&quot;,<br>            &quot;news&quot;,<br>            &quot;batch&quot;,      # NEW<br>        ]</pre><p>Similarly, when integrating role-based restrictions for EXP_USER and adding new test coverage, permission updates were isolated within the IsExpertUserRole class, other endpoints remained untouched. After merging to staging, all tests still passed, showing that clean separation of logic helped avoid regressions even during active development.</p><pre>// fe/expert-bulk-upload/page.tsx – akses EXP_USER dilokalisasi di satu halaman<br><br>const normalizeRole = (role?: string | null) =&gt; (role ? role.trim().toUpperCase() : &#39;&#39;);<br><br>export default function CuratorBulkUploadPage() {<br>  const { user } = useAuth();<br>  const router = useRouter();<br>  const [effectiveUser, setEffectiveUser] = useState(user ?? null);<br>  const [loading, setLoading] = useState(true);<br>  ...<br><br>  const role = normalizeRole(effectiveUser?.role);<br>  const isExpert = role === &#39;EXP_USER&#39; || role === &#39;ADMIN&#39;;<br><br>  ...<br><br>  // If authenticated but not EXP_USER, show AccessDenied with site chrome (navbar/footer)<br>  if (!loading &amp;&amp; effectiveUser &amp;&amp; !isExpert) {<br>    return (<br>      &lt;div className=&quot;min-h-screen bg-[#f0f6f8]&quot;&gt;<br>        &lt;Navbar /&gt;<br>        &lt;AccessDeniedNotice /&gt;<br>        &lt;Footer /&gt;<br>      &lt;/div&gt;<br>    );<br>  }</pre><p>From a teamwork standpoint, applying SRP and ISP made handoffs easier: Kevin could build the front-end uploader confidently without needing to understand backend internals. SOLID principles not only improved maintainability but also improved communication between backend and frontend developers.</p><pre>// fe/expert-bulk-upload/page.tsx – FE uploader cukup konsumsi komponen &amp; endpoint yang jelas<br><br>import CsvUpload from &#39;../components/CsvUpload&#39;;<br><br>...<br><br>// feedback UI dan behaviour dipisah dari detail HTTP di dalam CsvUpload<br>const handleSuccess = (m: string) =&gt; { setUploadFeedback({ status: &#39;success&#39;, msg: m }); };<br>const handleError = (e: string) =&gt; { setUploadFeedback({ status: &#39;error&#39;, msg: e }); };<br><br>...<br><br>&lt;CsvUpload<br>  effectiveUser={effectiveUser}<br>  onSuccessAction={handleSuccess}<br>  onErrorAction={handleError}<br>/&gt;</pre><h3>Final Reflection</h3><p>Working on Admin Role Management, Curator Add Data, and EXP_USER deepened my understanding that <strong>SOLID is not theoretical, it is structural discipline</strong>. SRP and OCP were applied consistently and produced tangible benefits, whereas DIP and LSP were only partially achieved due to the project’s architecture. Even so, this implementation improved modularity, reduced bugs during feature expansion, and made maintenance smoother. The experience demonstrated how thoughtful adherence to SOLID principles results in a stable, adaptable, and testable system over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c057b4398fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>