<?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 Emir Alicic on Medium]]></title>
        <description><![CDATA[Stories by Emir Alicic on Medium]]></description>
        <link>https://medium.com/@emir_75658?source=rss-205b446a4b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eDCw-xTipEcBwfc7N3RJEQ.png</url>
            <title>Stories by Emir Alicic on Medium</title>
            <link>https://medium.com/@emir_75658?source=rss-205b446a4b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:21:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emir_75658/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[Creating PDF Documents in Different Programming Languages]]></title>
            <link>https://medium.com/@emir_75658/creating-pdf-documents-in-different-programming-languages-67e43c8ea494?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/67e43c8ea494</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 07:06:26 GMT</pubDate>
            <atom:updated>2025-02-12T07:06:26.598Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article demonstrates how to start a simple, single-purpose project and utilize PDF libraries available in different programming languages. One library is chosen for each language, and the development process is described.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vlzuBYeHcNZBU-ZP" /></figure><h4>1. Selected Programming Languages and PDF Libraries</h4><p>For this article, four programming languages have been selected, with a single library chosen for each:</p><ul><li>JavaScript → PDFMake,</li><li>Java → Apache PDFBox,</li><li>Ruby → Prawn,</li><li>PHP → FPDF</li></ul><p>Following this article, you can start a simple command-line project in the respective programming language, install the selected PDF library as a dependency, and write code that utilizes the library to generate a custom PDF document.</p><h4>2. GitHub Repositories</h4><p>The implementations from this article are shared in the following GitHub repositories:</p><ul><li><a href="https://github.com/Gradient-s-p/create-pdf-using-javascript-and-pdfmake">JavaScript &amp; PDFMake</a>,</li><li><a href="https://github.com/Gradient-s-p/create-pdf-using-java-and-pdfbox">Java &amp; Apache PDFBox</a>,</li><li><a href="https://github.com/Gradient-s-p/create-pdf-using-ruby-and-prawn">Ruby &amp; Prawn</a>,</li><li><a href="https://github.com/Gradient-s-p/create-pdf-using-php-and-fpdf">PHP &amp; FPDF</a></li></ul><h4>3. Javascript &amp; PDFMake</h4><p>To start a new project in JavaScript, it is good practice to use a package manager. Node.js comes with the “npm” package manager by default. However, Yarn can be considered a more practical alternative (subjective opinion), so in this article Yarn is used. To install Yarn globally, run the following command:</p><pre>npm install -g yarn</pre><p>To initialize a new Node.js project, run the following command in the directory created for this project and answer the prompted questions about the project:</p><pre>yarn init<br>question name (create-pdf-using-javascript-and-pdfmake): <br>question version (1.0.0): <br>question description: <br>question entry point (index.js): <br>question repository url: <br>question author: Gradient s.p.<br>question license (MIT): <br>question private: <br>success Saved package.json<br>Done in 36.14s.</pre><p>At this point package.json file is generated.</p><p><em>package.json</em></p><pre>{<br>  &quot;name&quot;: &quot;create-pdf-using-javascript-and-pdfmake&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;author&quot;: &quot;Gradient s.p.&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;<br>}</pre><p>The “main” field in “package.json” is used when a project is intended to be used as an npm dependency in other projects. Since we are not building a library, but final program, we can remove “main” field. Additionally, we configure a run script for our project and create a simple ‘Hello World’ JavaScript program.</p><p><em>package.json</em></p><pre>{<br>  &quot;name&quot;: &quot;create-pdf-using-javascript-and-pdfmake&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/index.js&quot;<br>  },<br>  &quot;author&quot;: &quot;Gradient s.p.&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;<br>}</pre><p><em>src/index.js</em></p><pre>console.log(&quot;Hello World!&quot;);</pre><p>We then run it from the root of our project.</p><pre>yarn start<br><br>yarn run v1.22.22<br>$ node src/index.js<br>Hello World!<br>Done in 0.07s.</pre><p>The next step is to install the PDFMake library and create a simple ‘Hello World’ PDF file.</p><p><strong>Important:</strong> PDFMake requires font files to function. For this tutorial, you can download the necessary fonts <a href="https://fonts.google.com/selection?query=roboto">here</a> and save them in the <em>fonts/</em> directory. Refer to the following source code to see which font variants are needed for this example.</p><pre>yarn add pdfmake<br><br>yarn add v1.22.22<br>[1/4] Resolving packages...<br>[2/4] Fetching packages...<br>[3/4] Linking dependencies...<br>[4/4] Building fresh packages...<br><br>success Saved 1 new dependency.<br>info Direct dependencies<br>└─ pdfmake@0.2.18<br>info All dependencies<br>└─ pdfmake@0.2.18<br>Done in 0.47s.</pre><p><em>src/index.js</em></p><pre>import PdfPrinter from &quot;pdfmake&quot;;<br>import * as fs from &quot;fs&quot;;<br><br>const fonts = {<br>    Roboto: {<br>        normal: &#39;fonts/Roboto-Regular.ttf&#39;,<br>        bold: &#39;fonts/Roboto-Medium.ttf&#39;,<br>        italics: &#39;fonts/Roboto-Italic.ttf&#39;,<br>        bolditalics: &#39;fonts/Roboto-MediumItalic.ttf&#39;<br>    }<br>};<br><br>const printer = new PdfPrinter(fonts);<br><br>const docDefinition = {<br>    content: [<br>        // Content goes here<br>        {<br>            text: &quot;Hello World&quot;<br>        },<br>    ],<br>};<br><br>const options = {<br>    // General Options to be configured<br>}<br><br>const pdfDoc = printer.createPdfKitDocument(docDefinition, options);<br>pdfDoc.pipe(fs.createWriteStream(&#39;document.pdf&#39;));<br>pdfDoc.end();</pre><p>After executing the program, we obtain a basic ‘Hello World’ PDF.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*GYDvCIGpDrnoMIp9" /></figure><p>In PDFMake, content is defined in the docDefinition section as an array of elements that will be included in the PDF. Since the document definition is a single large JavaScript object, it is highly practical for dynamically generating the final PDF document.</p><p>One key advantage of PDFMake is its built-in handling of page breaks, which simplifies development when working with dynamically generated content, especially when the final document length is determined at runtime.</p><p>The following code demonstrates some of PDFMake’s features and builds a more complex PDF document:</p><p><em>src/index.js</em></p><pre>import PdfPrinter from &quot;pdfmake&quot;;<br>import * as fs from &quot;fs&quot;;<br><br>const fonts = {<br>    Roboto: {<br>        normal: &#39;fonts/Roboto-Regular.ttf&#39;,<br>        bold: &#39;fonts/Roboto-Medium.ttf&#39;,<br>        italics: &#39;fonts/Roboto-Italic.ttf&#39;,<br>        bolditalics: &#39;fonts/Roboto-MediumItalic.ttf&#39;<br>    }<br>};<br><br>const printer = new PdfPrinter(fonts);<br><br>const docDefinition = {<br>    styles: {<br>        heading: {<br>            fontSize: 18,<br>            bold: true,<br>            marginBottom: 20,<br>            marginTop: 20,<br>            alignment: &#39;center&#39;<br>        },<br>        content: {<br>            margin: [20, 0, 20, 5], // [left, top, right, bottom]<br>            alignment: &#39;justify&#39;,<br>            leadingIndent: 20<br>        }<br>    },<br>    content: [<br>        // Content goes here<br>        {<br>            text: &#39;Example document created using pdfmake&#39;,<br>            style: &#39;heading&#39;<br>        },<br>        {<br>            toc: {<br>                title: {text: &#39;INDEX&#39;, style: &#39;heading&#39;}<br>            }<br>        },<br>        {<br>            text: &#39;Topic 1&#39;,<br>            style: &#39;heading&#39;,<br>            tocItem: true<br>        },<br>        {<br>            text: &quot;Content of Topic 1. &quot;.repeat(40),<br>            style: &#39;content&#39;<br>        },<br>        {<br>            text: &quot;Content of Topic 1. &quot;.repeat(60),<br>            style: &#39;content&#39;<br>        },<br>        {<br>            text: &#39;Topic 2&#39;,<br>            style: &#39;heading&#39;,<br>            tocItem: true<br>        },<br>        {<br>            columns: [<br>                {<br>                    text: &quot;Content in Columns. &quot;.repeat(25),<br>                    style: &#39;content&#39;<br>                },<br>                {<br>                    text: &quot;Content in Columns. &quot;.repeat(25),<br>                    style: &#39;content&#39;<br>                }<br>            ]<br>        },<br>        {<br>            text: &#39;Topic 3&#39;,<br>            style: &#39;heading&#39;,<br>            tocItem: true<br>        },<br>        {<br>            text: &#39;Some Shapes&#39;,<br>            style: &#39;content&#39;<br>        },<br>        {<br>            canvas:<br>                [<br>                    {<br>                        type: &#39;line&#39;,<br>                        x1: 0, y1: 0,<br>                        x2: 260, y2: 60,<br>                        lineWidth: 3<br>                    },<br>                    {<br>                        type: &#39;polyline&#39;,<br>                        lineWidth: 3,<br>                        closePath: true,<br>                        lineColor: &#39;blue&#39;,<br>                        color: &#39;red&#39;,<br>                        points: [{ x: 310, y: 10}, { x: 335, y: 40 }, { x: 400, y: 40 }, { x: 425, y:10 }]<br>                    }<br>                ]<br>        }<br>    ],<br>};<br><br>const options = {<br>    // General Options to be configured<br>}<br><br>const pdfDoc = printer.createPdfKitDocument(docDefinition, options);<br>pdfDoc.pipe(fs.createWriteStream(&#39;document.pdf&#39;));<br>pdfDoc.end();</pre><p>This implementation produces following PDF document:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*t_wdY0yDxuBi1Lsz" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*lo0e0jqI177TG7kk" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*b72K__cZExrWEhlI" /></figure><p>For more details on using and configuring PDFMake, visit their <a href="http://pdfmake.org/">official website</a>.</p><h4>4. Java &amp; Apache PDFBox</h4><p>In this section, we will build a Java example project using Gradle, a Java build tool.</p><p>To initialize a new Java project, run the following command in the directory created for this project and answer the prompted questions about the project:</p><pre>gradle init --type java-application<br><br>Select build script DSL:<br>  1: Groovy<br>  2: Kotlin<br>Enter selection (default: Groovy) [1..2] <br><br>Select test framework:<br>  1: JUnit 4<br>  2: TestNG<br>  3: Spock<br>  4: JUnit Jupiter<br>Enter selection (default: JUnit Jupiter) [1..4] <br><br>Project name (default: create-pdf-using-java-and-pdfbox): <br><br>Source package (default: create.pdf.using.java.and.pdfbox): <br><br>&gt; Task :init<br>Get more help with your project: https://docs.gradle.org/7.2/samples/sample_building_java_applications.html<br><br>BUILD SUCCESSFUL in 10s<br>2 actionable tasks: 2 executed</pre><p>As a result of the initialization, a basic ‘Hello World’ application is created.</p><p><em>App.java</em></p><pre>/*<br> * This Java source file was generated by the Gradle &#39;init&#39; task.<br> */<br>package create.pdf.using.java.and.pdfbox;<br><br>public class App {<br>    public String getGreeting() {<br>        return &quot;Hello World!&quot;;<br>    }<br><br>    public static void main(String[] args) {<br>        System.out.println(new App().getGreeting());<br>    }<br>}</pre><p>To build the test project and run all checks, execute the Gradle build task:</p><pre>./gradlew build</pre><p>To run the project (including compilation):</p><pre>./gradlew run<br><br>&gt; Task :app:run<br>Hello World!<br><br>BUILD SUCCESSFUL in 619ms<br>2 actionable tasks: 1 executed, 1 up-to-date</pre><p>To ensure the same Gradle version is configured as used in this article, make sure the ‘distributionUrl’ parameter matches.</p><p>gradle/wrapper/gradle-wrapper.properties</p><pre>distributionBase=GRADLE_USER_HOME<br>distributionPath=wrapper/dists<br>distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip<br>zipStoreBase=GRADLE_USER_HOME<br>zipStorePath=wrapper/dists</pre><p>After the correct configuration, adding the Apache PDFBox dependency is required.</p><p><em>app/build.gradle</em></p><pre>... other build settings<br><br>dependencies {<br>   ... other dependencies<br><br>    // https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox<br>    implementation group: &#39;org.apache.pdfbox&#39;, name: &#39;pdfbox&#39;, version: &#39;3.0.4&#39;<br>}</pre><p>The build should succeed after this step (./gradlew build), and then the PDF creation implementation can be added.</p><p><em>App.java</em></p><pre>package create.pdf.using.java.and.pdfbox;<br><br>import org.apache.pdfbox.pdmodel.PDDocument;<br>import org.apache.pdfbox.pdmodel.PDPage;<br>import org.apache.pdfbox.pdmodel.PDPageContentStream;<br>import org.apache.pdfbox.pdmodel.font.PDType1Font;<br>import org.apache.pdfbox.pdmodel.font.Standard14Fonts;<br><br>import java.io.IOException;<br><br>public class App {<br>    public static void main(String[] args) throws IOException {<br>        App app = new App();<br>        final int fontSize = 12;<br>        final int margin = 50;<br>        final int leading = fontSize + 2;<br><br>        PDDocument document = new PDDocument();<br><br>        PDPage page = new PDPage();<br><br>        PDPageContentStream contentStream = new PDPageContentStream(document, page);<br><br>        app.drawCircle(contentStream, margin, page.getBBox().getHeight() - margin, margin, 0.8f, 0, 0);<br>        app.drawCircle(contentStream, page.getBBox().getWidth() - margin, page.getBBox().getHeight() - margin, margin, 0, 0, 0.8f);<br><br>        contentStream.beginText();<br>        contentStream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), fontSize);<br>        contentStream.newLineAtOffset(margin, page.getBBox().getHeight() - margin);<br>        contentStream.setLeading(leading);<br>        contentStream.setNonStrokingColor(0, 0, 0);<br><br>        for (int j = 1; j &lt; 5; j++) {<br>            for (int i = 1; i &lt; 6; i++) {<br>                StringBuilder sb = new StringBuilder();<br><br>                app.drawLineOfText(contentStream, sb.append(&quot;Example Text &quot;)<br>                        .append(i)<br>                        .append(&quot; &quot;)<br>                        .toString()<br>                        .repeat(i)<br>                );<br>            }<br><br>            app.drawLineOfText(contentStream, &quot;&quot;);<br>        }<br><br>        document.addPage(page);<br><br>        contentStream.close();<br>        document.save(&quot;my_doc.pdf&quot;);<br>        System.out.println(&quot;PDF Created&quot;);<br><br>        document.close();<br>    }<br><br>    private void drawLineOfText(PDPageContentStream contentStream, String text) throws IOException {<br>        contentStream.showText(text);<br>        contentStream.newLine();<br>    }<br><br>    private void drawCircle(PDPageContentStream contentStream, float cx, float cy, float r, float red, float green, float blue) throws IOException {<br>        final float k = 0.552284749831f;<br>        contentStream.setJavaNonStrokingColor(red, green, blue);<br>        contentStream.moveTo(cx - r, cy);<br>        contentStream.curveTo(cx - r, cy + k * r, cx - k * r, cy + r, cx, cy + r);<br>        contentStream.curveTo(cx + k * r, cy + r, cx + r, cy + k * r, cx + r, cy);<br>        contentStream.curveTo(cx + r, cy - k * r, cx + k * r, cy - r, cx, cy - r);<br>        contentStream.curveTo(cx - k * r, cy - r, cx - r, cy - k * r, cx - r, cy);<br>        contentStream.fill();<br>    }<br>}</pre><p>This implementation produces following PDF document:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*UobC1JI1CfG5u4kS" /></figure><h4>5. Ruby &amp; Prawn</h4><p>In this section, we will create a Ruby example project using Bundler as a package manager.</p><p>To initialize a new Ruby project, run the following commands in the directory created for this project:</p><pre>&gt; bundle init<br><br>&gt; bundle add prawn<br><br>&gt; bundle install</pre><p>As a result, the Gemfile should be created with content similar to the following:</p><p><em>Gemfile</em></p><pre># frozen_string_literal: true<br><br>source &quot;https://rubygems.org&quot;<br><br># gem &quot;rails&quot;<br><br>gem &quot;prawn&quot;, &quot;~&gt; 2.5&quot;</pre><p>Now, create a directory named src, and inside it, create the following file for a Hello World example:</p><p><em>src/main.rb</em></p><pre># frozen_string_literal: true<br><br>require &quot;prawn&quot;<br><br>Prawn::Document.generate(&quot;hello.pdf&quot;) do<br>  text &quot;Hello World!&quot;<br>end</pre><p>Run this program with the following command:</p><pre>ruby src/main.rb</pre><p>After execution, a PDF named hello.pdf is created in the root directory. It looks as follows:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*4r-oUs7IvuCS4nJv" /></figure><p>When everything is ready, we can build our PDF example using Ruby and Prawn. Here is the source code that generates it:</p><p><em>src/main.rb</em></p><pre># frozen_string_literal: true<br><br>require &quot;prawn&quot;<br><br>Prawn::Document.generate(&quot;document.pdf&quot;) do<br>  text &quot;Hello World!&quot;<br><br>  text &#39;Section 1&#39;,<br>       size: 24,<br>       align: :center<br><br>  text &#39;Content for first section. &#39; * 10<br><br>  text &#39;Section 2&#39;,<br>       size: 24,<br>       align: :center<br><br>  column_box([0, cursor], columns: 2, width: bounds.width) do<br>    text(&quot;#{&lt;&lt;~TEXT.gsub(/\s+/, &#39; &#39;)}\n\n&quot; * 4)<br>    All the States and Governments by which men are or ever have been ruled,<br>                                                                      have been and are either Republics or Princedoms. Princedoms are either<br>    hereditary, in which the sovereignty is derived through an ancient line<br>    of ancestors, or they are new. New Princedoms are either wholly new, as<br>    that of Milan to Francesco Sforza; or they are like limbs joined on to<br>    the hereditary possessions of the Prince who acquires them, as the<br>    Kingdom of Naples to the dominions of the King of Spain. The States thus<br>    acquired have either been used to live under a Prince or have been free;<br>    and he who acquires them does so either by his own arms or by the arms of<br>    others, and either by good fortune or by merit.<br>      TEXT<br>  end<br><br>  text &#39;Section 3 - Drawing&#39;,<br>       size: 24,<br>       align: :center<br><br>  bounding_box([100, cursor], width: 300, height: 100) do<br>    stroke_bounds<br>    stroke_circle [0, 0], 10<br>  end<br><br>  stroke_axis<br><br>  stroke do<br>    move_to 0, 0<br>    line_to 100, 100<br>    line_to 0, 100<br>    curve_to [150, 200], bounds: [[20, 150], [120, 150]]<br>    curve_to [200, 0], bounds: [[150, 200], [450, 10]]<br>  end<br><br>  fill_ellipse [200, 500], 100, 50<br><br>end</pre><p>This example results in the following PDF document:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*p11bQKqWd0W4wgWa" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*N-5gPGWGSJEgfe4B" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*hG8XtnSGPjhKbFxm" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*qvzXu4ffBq3iJr25" /></figure><h4>6. PHP &amp; FPDF</h4><p>In this section, we will build a PHP example project using Composer, a PHP build tool.</p><p>To initialize a new PHP project, run the following command in the directory created for this project, and answer the prompted questions about the project.</p><pre>&gt; composer init<br><br># or alternatively<br><br>&gt; php composer.phar init</pre><p>After this, for simplicity, open composer.json and remove the default PSR-4 namespaces so that the resulting file looks as follows:</p><p><em>composer.json</em></p><pre>{<br>    &quot;name&quot;: &quot;gradient/create-pdf-using-php-and-fpdf&quot;<br>}</pre><p>It is time to add the FPDF dependency and create a Hello World PDF. The command is:</p><pre>composer require fpdf/fpdf<br><br># or alternatively<br><br>php composer.phar require fpdf/fpdf</pre><p><em>src/main.php</em></p><pre>&lt;?php<br><br>require __DIR__ . &#39;/../vendor/autoload.php&#39;;<br>use Fpdf\Fpdf;<br><br>$fpdf = new Fpdf();<br><br>$fpdf-&gt;AddPage();<br>$fpdf-&gt;SetFont(&#39;Arial&#39;, &#39;&#39;, 16);<br>$fpdf-&gt;Write(0, &#39;Hello World!&#39;);<br>$fpdf-&gt;Output(&#39;F&#39;, getcwd() . DIRECTORY_SEPARATOR . &#39;document.pdf&#39;);</pre><p>Run this program with the following command:</p><pre>php src/main.php</pre><p>As a result, the file document.pdf should be created, and it looks as follows:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*rLQmJak8wqpirLOR" /></figure><p>If everything works correctly, the next step is to build the resulting example PDF document. The code example we will use is:</p><p><em>src/main.php</em></p><pre>&lt;?php<br><br>require __DIR__ . &#39;/../vendor/autoload.php&#39;;<br>use Fpdf\Fpdf;<br><br>$regularTextSize = 16;<br>$titleTextSize = 32;<br><br>$fpdf = new Fpdf();<br><br>$fpdf-&gt;AddPage();<br>$fpdf-&gt;SetFont(&#39;Arial&#39;, &#39;&#39;, $regularTextSize);<br><br>$fpdf-&gt;Write($regularTextSize, &quot;Hello World!\n&quot;);<br><br>$fpdf-&gt;SetFont(&#39;Arial&#39;, &#39;b&#39;, $titleTextSize);<br>$fpdf-&gt;Cell(0, $titleTextSize / 2, &quot;Section 1&quot;, null, null, &#39;C&#39;);<br>$fpdf-&gt;Ln();<br><br>$fpdf-&gt;SetFont(&#39;Arial&#39;, &#39;&#39;, $regularTextSize);<br>$fpdf-&gt;Write($regularTextSize / 2, str_repeat(&#39;Section 1 Content. &#39;, 10));<br>$fpdf-&gt;Ln();<br>$fpdf-&gt;Ln();<br><br>$fpdf-&gt;Write($regularTextSize / 2, &#39;Some additional Text&#39;);<br>$fpdf-&gt;Ln();<br><br>$triangleHeight = 20;<br>$point1 = [0, $fpdf-&gt;GetY()];<br>$point2 = [$fpdf-&gt;GetPageWidth() / 2, $fpdf-&gt;GetY() + $triangleHeight];<br>$point3 = [$fpdf-&gt;GetPageWidth(), $fpdf-&gt;GetY()];<br><br>$fpdf-&gt;Line(...$point1, ...$point2);<br>$fpdf-&gt;Line(...$point2, ...$point3);<br>$fpdf-&gt;Line(...$point3, ...$point1);<br><br>$fpdf-&gt;Output(&#39;F&#39;, getcwd() . DIRECTORY_SEPARATOR . &#39;document.pdf&#39;);</pre><p>This code results in the following PDF:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*1n9T85IEUNNjPQGn" /></figure><h4>7. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next development project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67e43c8ea494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom Features Leveraging QuickBooks Data via API Integration]]></title>
            <link>https://medium.com/@emir_75658/building-custom-features-leveraging-quickbooks-data-via-api-integration-2e5dbd458e1f?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e5dbd458e1f</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[custom-feature]]></category>
            <category><![CDATA[quickbooks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 14:17:49 GMT</pubDate>
            <atom:updated>2025-02-12T09:54:13.506Z</atom:updated>
            <content:encoded><![CDATA[<h4>QuickBooks simplifies small business accounting by automating tasks such as bookkeeping, invoicing, time tracking, sales tax management, budgeting, bank reconciliation, and inventory tracking. While it offers a wide range of features and remarkable flexibility, some specific business scenarios may fall outside its built-in capabilities. To address these gaps, utilizing QuickBooks’ API to integrate the required functionality is a practical and effective solution.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*5mRISjhhRmE06xWH" /></figure><h4>1. Custom Reporting: Average Monthly Revenue by Customer</h4><p>Throughout this article, we will develop a software solution designed to provide insights into customer performance by calculating the average monthly revenue generated by each customer. This report enables businesses to identify high-performing clients, uncover trends, and make data-driven decisions to optimize revenue strategies.</p><p>The reporting methodology will calculate the average monthly revenue over the entire duration of the customer relationship. The starting point for the calculation will be the month of the first issued invoice, while the endpoint will be the month of the last issued invoice. This approach focuses on providing an average revenue figure across the full timespan of cooperation, rather than per-month insights.</p><p>For example, if a customer has two invoices — one issued in January 2024 and the other (the last) in December 2024 — the average will be calculated over a 12-month period. The total revenue from the invoices will be summed and then divided by 12 (the total number of months) to determine the average monthly revenue.</p><h4>2. GitHub Repository</h4><p>There is one solution presented in this article and complete implementation of solution shown in this article can be cloned from GitHub repository: <a href="https://github.com/Gradient-s-p/custom-quickbooks-report">https://github.com/Gradient-s-p/custom-quickbooks-report</a>.</p><h4>3. Ensuring That Necessary Data Is Available</h4><p>To build the desired custom report successfully, we need the following data:</p><ul><li>Invoicing data, specifically the invoice date, totals, and the connection to the customer the invoice is issued to.</li><li>Customer data, specifically the first name, last name, and address for B2C services, or the company name and address for B2B services.</li></ul><p>Before proceeding with this article, ensure that you have signed up for and logged in to your Intuit Developer account by following the guidelines <a href="https://developer.intuit.com/app/developer/qbdesktop/docs/get-started/create-an-intuit-developer-account">here</a>.</p><h4>4. Invoice Data API</h4><p>By reviewing the API documentation, we can locate the endpoint for querying invoices, which is documented <a href="https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/invoice#query-an-invoice">here</a>. The documentation includes an interactive test feature that allows us to query all invoices. This functionality is demonstrated in the following screenshot:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*Gv97mnWVxaoAivWU" /></figure><p>Sample query is:</p><pre>select * from Invoice</pre><p>Result is:</p><pre>{<br> &quot;QueryResponse&quot;: {<br>  &quot;Invoice&quot;: [<br>   {<br>    &quot;AllowIPNPayment&quot;: false,<br>    &quot;AllowOnlinePayment&quot;: false,<br>    &quot;AllowOnlineCreditCardPayment&quot;: false,<br>    &quot;AllowOnlineACHPayment&quot;: false,<br>    &quot;domain&quot;: &quot;QBO&quot;,<br>    &quot;sparse&quot;: false,<br>    &quot;Id&quot;: &quot;146&quot;,<br>    &quot;SyncToken&quot;: &quot;0&quot;,<br>    &quot;MetaData&quot;: {<br>     &quot;CreateTime&quot;: &quot;2025-01-09T01:40:36-08:00&quot;,<br>     &quot;LastModifiedByRef&quot;: {<br>      &quot;value&quot;: &quot;9341453764932177&quot;<br>     },<br>     &quot;LastUpdatedTime&quot;: &quot;2025-01-09T01:40:36-08:00&quot;<br>    },<br>    &quot;CustomField&quot;: [],<br>    &quot;DocNumber&quot;: &quot;1039&quot;,<br>    &quot;TxnDate&quot;: &quot;2025-01-09&quot;,<br>    &quot;CurrencyRef&quot;: {<br>     &quot;value&quot;: &quot;EUR&quot;,<br>     &quot;name&quot;: &quot;Euro&quot;<br>    },<br>    &quot;ExchangeRate&quot;: 1.02941,<br>    &quot;LinkedTxn&quot;: [],<br>    &quot;Line&quot;: [<br>     {<br>      &quot;Id&quot;: &quot;1&quot;,<br>      &quot;LineNum&quot;: 1,<br>      &quot;Description&quot;: &quot;Weekly Gardening Service&quot;,<br>      &quot;Amount&quot;: 1000,<br>      &quot;DetailType&quot;: &quot;SalesItemLineDetail&quot;,<br>      &quot;SalesItemLineDetail&quot;: {<br>       &quot;ItemRef&quot;: {<br>        &quot;value&quot;: &quot;6&quot;,<br>        &quot;name&quot;: &quot;Gardening&quot;<br>       },<br>       &quot;UnitPrice&quot;: 100,<br>       &quot;Qty&quot;: 10,<br>       &quot;ItemAccountRef&quot;: {<br>        &quot;value&quot;: &quot;45&quot;,<br>        &quot;name&quot;: &quot;Landscaping Services&quot;<br>       },<br>       &quot;TaxCodeRef&quot;: {<br>        &quot;value&quot;: &quot;NON&quot;<br>       }<br>      }<br>     },<br>     {<br>      &quot;Amount&quot;: 1000,<br>      &quot;DetailType&quot;: &quot;SubTotalLineDetail&quot;,<br>      &quot;SubTotalLineDetail&quot;: {}<br>     }<br>    ],<br>    &quot;TxnTaxDetail&quot;: {<br>     &quot;TotalTax&quot;: 0<br>    },<br>    &quot;CustomerRef&quot;: {<br>     &quot;value&quot;: &quot;58&quot;,<br>     &quot;name&quot;: &quot;Mr Abc Bcd Cde&quot;<br>    },<br>    &quot;CustomerMemo&quot;: {<br>     &quot;value&quot;: &quot;Thank you for your business and have a great day!&quot;<br>    },<br>    &quot;BillAddr&quot;: {<br>     &quot;Id&quot;: &quot;96&quot;,<br>     &quot;City&quot;: &quot;Berlin&quot;,<br>     &quot;Country&quot;: &quot;Germany&quot;<br>    },<br>    &quot;ShipAddr&quot;: {<br>     &quot;Id&quot;: &quot;96&quot;,<br>     &quot;City&quot;: &quot;Berlin&quot;,<br>     &quot;Country&quot;: &quot;Germany&quot;<br>    },<br>    &quot;FreeFormAddress&quot;: false,<br>    &quot;SalesTermRef&quot;: {<br>     &quot;value&quot;: &quot;3&quot;,<br>     &quot;name&quot;: &quot;Net 30&quot;<br>    },<br>    &quot;DueDate&quot;: &quot;2025-02-08&quot;,<br>    &quot;TotalAmt&quot;: 1000,<br>    &quot;HomeTotalAmt&quot;: 1029.41,<br>    &quot;ApplyTaxAfterDiscount&quot;: false,<br>    &quot;PrintStatus&quot;: &quot;NeedToPrint&quot;,<br>    &quot;EmailStatus&quot;: &quot;NotSet&quot;,<br>    &quot;Balance&quot;: 1000,<br>    &quot;HomeBalance&quot;: 1029.41<br>   },<br>   // ... other Invoice records<br>  ],<br>  &quot;startPosition&quot;: 1,<br>  &quot;maxResults&quot;: 33,<br>  &quot;totalCount&quot;: 33<br> },<br> &quot;time&quot;: &quot;2025-01-09T06:12:09.174-08:00&quot;<br>}</pre><p>At the end of the response, there are attributes such as startPosition, maxResults, and totalCount. These attributes are useful for pagination when importing all invoices. One possible approach is to use the following query:</p><pre>select count(*) from Invoice</pre><p>Result is:</p><pre>{<br> &quot;QueryResponse&quot;: {<br>  &quot;totalCount&quot;: 33<br> },<br> &quot;time&quot;: &quot;2025-01-09T06:49:56.354-08:00&quot;<br>}</pre><p>After getting the count, we can decide on page size, and execute queries as following:</p><pre>select * from Invoice maxResults 5 startPosition 1<br>select * from Invoice maxResults 5 startPosition 6<br>select * from Invoice maxResults 5 startPosition 11</pre><p>With these results, it is clear that we can retrieve all the necessary invoice data for our task using the QuickBooks API.</p><h4>5. Customer Data API</h4><p>In the invoice responses, we can locate Customer Reference data, which includes the qualified customer name and its ID in the value attribute. Additional data related to the invoiced service, such as the billing or delivery address, is also provided. For our purposes, this may be sufficient to connect a customer with their address.</p><p>It is important to note, however, that the billing and delivery addresses in the invoice response reflect the information assigned to the customer at the time the invoice was created. These addresses may differ from the customer’s current address when generating the report discussed in this article.</p><p>To obtain up-to-date customer and address information, we should use the Customer Data API, which can be explored here. Querying customer data can also be tested in the following documentation section:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*6QPfPp23coABNfr3" /></figure><p>After fetching the necessary invoices, we can use the associated Customer IDs to execute queries and retrieve specific customer data:</p><pre>select * from Customer Where id IN (&#39;1&#39;, &#39;2&#39;, &#39;4&#39;)</pre><p>With the result:</p><pre>{<br> &quot;QueryResponse&quot;: {<br>  &quot;Customer&quot;: [<br>   {<br>    &quot;Taxable&quot;: true,<br>    &quot;BillAddr&quot;: {<br>     &quot;Id&quot;: &quot;2&quot;,<br>     &quot;Line1&quot;: &quot;4581 Finch St.&quot;,<br>     &quot;City&quot;: &quot;Bayshore&quot;,<br>     &quot;CountrySubDivisionCode&quot;: &quot;CA&quot;,<br>     &quot;PostalCode&quot;: &quot;94326&quot;,<br>     &quot;Lat&quot;: &quot;INVALID&quot;,<br>     &quot;Long&quot;: &quot;INVALID&quot;<br>    },<br>    &quot;ShipAddr&quot;: {<br>     &quot;Id&quot;: &quot;2&quot;,<br>     &quot;Line1&quot;: &quot;4581 Finch St.&quot;,<br>     &quot;City&quot;: &quot;Bayshore&quot;,<br>     &quot;CountrySubDivisionCode&quot;: &quot;CA&quot;,<br>     &quot;PostalCode&quot;: &quot;94326&quot;,<br>     &quot;Lat&quot;: &quot;INVALID&quot;,<br>     &quot;Long&quot;: &quot;INVALID&quot;<br>    },<br>    &quot;Job&quot;: false,<br>    &quot;BillWithParent&quot;: false,<br>    &quot;Balance&quot;: 239,<br>    &quot;BalanceWithJobs&quot;: 239,<br>    &quot;CurrencyRef&quot;: {<br>     &quot;value&quot;: &quot;USD&quot;,<br>     &quot;name&quot;: &quot;United States Dollar&quot;<br>    },<br>    &quot;PreferredDeliveryMethod&quot;: &quot;Print&quot;,<br>    &quot;IsProject&quot;: false,<br>    &quot;ClientEntityId&quot;: &quot;0&quot;,<br>    &quot;domain&quot;: &quot;QBO&quot;,<br>    &quot;sparse&quot;: false,<br>    &quot;Id&quot;: &quot;1&quot;,<br>    &quot;SyncToken&quot;: &quot;0&quot;,<br>    &quot;MetaData&quot;: {<br>     &quot;CreateTime&quot;: &quot;2024-12-06T16:48:43-08:00&quot;,<br>     &quot;LastUpdatedTime&quot;: &quot;2024-12-13T13:39:32-08:00&quot;<br>    },<br>    &quot;GivenName&quot;: &quot;Amy&quot;,<br>    &quot;FamilyName&quot;: &quot;Lauterbach&quot;,<br>    &quot;FullyQualifiedName&quot;: &quot;Amy&#39;s Bird Sanctuary&quot;,<br>    &quot;CompanyName&quot;: &quot;Amy&#39;s Bird Sanctuary&quot;,<br>    &quot;DisplayName&quot;: &quot;Amy&#39;s Bird Sanctuary&quot;,<br>    &quot;PrintOnCheckName&quot;: &quot;Amy&#39;s Bird Sanctuary&quot;,<br>    &quot;Active&quot;: true,<br>    &quot;V4IDPseudonym&quot;: &quot;0020984269d61f380843669fe5bd7044f5ff0d&quot;,<br>    &quot;PrimaryPhone&quot;: {<br>     &quot;FreeFormNumber&quot;: &quot;(650) 555-3311&quot;<br>    },<br>    &quot;PrimaryEmailAddr&quot;: {<br>     &quot;Address&quot;: &quot;Birds@Intuit.com&quot;<br>    }<br>   },<br>   {<br>    &quot;Taxable&quot;: false,<br>    &quot;BillAddr&quot;: {<br>     &quot;Id&quot;: &quot;3&quot;,<br>     &quot;Line1&quot;: &quot;12 Ocean Dr.&quot;,<br>     &quot;City&quot;: &quot;Half Moon Bay&quot;,<br>     &quot;CountrySubDivisionCode&quot;: &quot;CA&quot;,<br>     &quot;PostalCode&quot;: &quot;94213&quot;,<br>     &quot;Lat&quot;: &quot;37.4307072&quot;,<br>     &quot;Long&quot;: &quot;-122.4295234&quot;<br>    },<br>    &quot;Job&quot;: false,<br>    &quot;BillWithParent&quot;: false,<br>    &quot;Balance&quot;: 85,<br>    &quot;BalanceWithJobs&quot;: 85,<br>    &quot;CurrencyRef&quot;: {<br>     &quot;value&quot;: &quot;USD&quot;,<br>     &quot;name&quot;: &quot;United States Dollar&quot;<br>    },<br>    &quot;PreferredDeliveryMethod&quot;: &quot;Print&quot;,<br>    &quot;IsProject&quot;: false,<br>    &quot;ClientEntityId&quot;: &quot;0&quot;,<br>    &quot;domain&quot;: &quot;QBO&quot;,<br>    &quot;sparse&quot;: false,<br>    &quot;Id&quot;: &quot;2&quot;,<br>    &quot;SyncToken&quot;: &quot;0&quot;,<br>    &quot;MetaData&quot;: {<br>     &quot;CreateTime&quot;: &quot;2024-12-06T16:49:28-08:00&quot;,<br>     &quot;LastUpdatedTime&quot;: &quot;2024-12-13T12:56:01-08:00&quot;<br>    },<br>    &quot;GivenName&quot;: &quot;Bill&quot;,<br>    &quot;FamilyName&quot;: &quot;Lucchini&quot;,<br>    &quot;FullyQualifiedName&quot;: &quot;Bill&#39;s Windsurf Shop&quot;,<br>    &quot;CompanyName&quot;: &quot;Bill&#39;s Windsurf Shop&quot;,<br>    &quot;DisplayName&quot;: &quot;Bill&#39;s Windsurf Shop&quot;,<br>    &quot;PrintOnCheckName&quot;: &quot;Bill&#39;s Windsurf Shop&quot;,<br>    &quot;Active&quot;: true,<br>    &quot;V4IDPseudonym&quot;: &quot;0020987f7bbe58b72a4343bc45437a189f23f2&quot;,<br>    &quot;PrimaryPhone&quot;: {<br>     &quot;FreeFormNumber&quot;: &quot;(415) 444-6538&quot;<br>    },<br>    &quot;PrimaryEmailAddr&quot;: {<br>     &quot;Address&quot;: &quot;Surf@Intuit.com&quot;<br>    }<br>   },<br>   {<br>    &quot;Taxable&quot;: false,<br>    &quot;BillAddr&quot;: {<br>     &quot;Id&quot;: &quot;5&quot;,<br>     &quot;Line1&quot;: &quot;321 Channing&quot;,<br>     &quot;City&quot;: &quot;Palo Alto&quot;,<br>     &quot;CountrySubDivisionCode&quot;: &quot;CA&quot;,<br>     &quot;PostalCode&quot;: &quot;94303&quot;,<br>     &quot;Lat&quot;: &quot;37.443231&quot;,<br>     &quot;Long&quot;: &quot;-122.1561846&quot;<br>    },<br>    &quot;Job&quot;: false,<br>    &quot;BillWithParent&quot;: false,<br>    &quot;Balance&quot;: 0,<br>    &quot;BalanceWithJobs&quot;: 0,<br>    &quot;CurrencyRef&quot;: {<br>     &quot;value&quot;: &quot;USD&quot;,<br>     &quot;name&quot;: &quot;United States Dollar&quot;<br>    },<br>    &quot;PreferredDeliveryMethod&quot;: &quot;Print&quot;,<br>    &quot;IsProject&quot;: false,<br>    &quot;ClientEntityId&quot;: &quot;0&quot;,<br>    &quot;domain&quot;: &quot;QBO&quot;,<br>    &quot;sparse&quot;: false,<br>    &quot;Id&quot;: &quot;4&quot;,<br>    &quot;SyncToken&quot;: &quot;0&quot;,<br>    &quot;MetaData&quot;: {<br>     &quot;CreateTime&quot;: &quot;2024-12-06T16:52:08-08:00&quot;,<br>     &quot;LastUpdatedTime&quot;: &quot;2024-12-06T16:52:08-08:00&quot;<br>    },<br>    &quot;GivenName&quot;: &quot;Diego&quot;,<br>    &quot;FamilyName&quot;: &quot;Rodriguez&quot;,<br>    &quot;FullyQualifiedName&quot;: &quot;Diego Rodriguez&quot;,<br>    &quot;DisplayName&quot;: &quot;Diego Rodriguez&quot;,<br>    &quot;PrintOnCheckName&quot;: &quot;Diego Rodriguez&quot;,<br>    &quot;Active&quot;: true,<br>    &quot;V4IDPseudonym&quot;: &quot;002098bfad66f678f04c12815ec338f55556e5&quot;,<br>    &quot;PrimaryPhone&quot;: {<br>     &quot;FreeFormNumber&quot;: &quot;(650) 555-4477&quot;<br>    },<br>    &quot;PrimaryEmailAddr&quot;: {<br>     &quot;Address&quot;: &quot;Diego@Rodriguez.com&quot;<br>    }<br>   }<br>  ],<br>  &quot;startPosition&quot;: 1,<br>  &quot;maxResults&quot;: 3<br> },<br> &quot;time&quot;: &quot;2025-01-10T03:18:11.010-08:00&quot;<br>}</pre><p>The up-to-date billing address is now available, and the presence of the companyName field allows us to distinguish between business customers (B2B) and individual customers (B2C). With this data in hand, all prerequisites for building the custom reporting tool are fulfilled.</p><h4>6. Developer Application and Authorization</h4><p>In this article, we will build a command-line utility to generate the desired report. Instead of fully implementing OAuth2, as required by QuickBooks, we will leverage their available playground for authorization.</p><p>For a complete authorization process, we would need a web application capable of handling authorization requests, and managing access and refresh tokens. This is likely a topic for one of the future articles.</p><p>To ensure successful operation, you need to create your own Developer Application and use the QuickBooks playground to retrieve an access token, which will be required later. Guidelines on how to complete this process are provided <a href="https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0-playground">here</a>.</p><p>Once everything is correctly configured, you should be able to retrieve an access token, as shown in the following screenshot.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*5LSI-cnuzHoZsXJi" /></figure><h4>7. Structuring Code and Making the First API Call</h4><p>In the empty source code directory, we will create a directory named “customersreport”, where all incorporated classes will be placed. This directory will include the following three classes:</p><ul><li>QuickBooksClient: A class responsible for handling all communication with the QuickBooks API, including data fetching.</li><li>DataProcessor: A class that processes and maps data necessary for building the final report.</li><li>PdfReport: A class dedicated to creating the final PDF report based on the provided data.</li></ul><p>In the root of our project, we will prepare the following files:</p><ul><li>main.py: The entry point of our program.</li><li>.env and .env.template: Files for storing environment variables.</li></ul><p>Additionally, it is recommended to access the repository shared in this article (or here) to download the requirements.txt file, which contains all the dependencies needed for the project. Save this file in the root directory of the project.</p><p>Install all dependencies by running the following command in the root directory of the project:</p><pre>pip install -r requirements.txt</pre><p>Since every developer and running environment may have different settings, the .env file is included in .gitignore to ensure it is not shared between instances. Instead, the .env.template file is shared and serves as a reference, listing all the settings required to run the program.</p><p>The contents of these files are as follows:</p><p><em>.env.template</em></p><pre>QUICKBOOKS_BASE_URL=<br>COMPANY_ID=<br>ACCESS_TOKEN=</pre><p><em>.env</em></p><pre>QUICKBOOKS_BASE_URL=https://sandbox-quickbooks.api.intuit.com<br>QUICKBOOKS_COMPANY_ID=9341453764932151<br>QUICKBOOKS_ACCESS_TOKEN=eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..IqlJruvUM5jejkARctj...</pre><p>(This file contains the actual values, which are unique to each environment and should not be shared.)</p><p>Short description of environment variables:</p><ul><li>QUICKBOOKS_BASE_URL: The QuickBooks API URL (sandbox and production URLs are different).</li><li>QUICKBOOKS_COMPANY_ID: The Company ID, often referred to as the Realm ID in QuickBooks documentation.</li><li>QUICKBOOKS_ACCESS_TOKEN: The token used to authorize access to the necessary endpoints in the QuickBooks API.</li></ul><p>To make the initial API request, we prepare the following class:</p><p><em>customersreport/quickbooks_client.py</em></p><pre>import requests<br><br>class QuickbooksClient:<br>    def __init__(self, base_url, company_id, access_token):<br>        self.access_token = access_token<br>        self.base_url = base_url<br>        self.company_id = company_id<br><br>    def load_invoices(self):<br>        url = f&quot;{self.base_url}/v3/company/{self.company_id}/query&quot;<br><br>        try:<br>            response = requests.get(<br>                url,<br>                headers={<br>                    &#39;Accept&#39;: &#39;application/json&#39;,<br>                    &#39;Authorization&#39;: f&#39;Bearer {self.access_token}&#39;<br>                },<br>                params={<br>                    &#39;query&#39;: &#39;select * from Invoice&#39;<br>                }<br>            )<br>            return response.json()<br><br>        except requests.exceptions.RequestException as e:<br>            print(&#39;Error:&#39;, e)<br>            return None</pre><p>To invoke this class and log the results of fetching invoices, we prepare the main.py file as the entry point of our project.</p><p><em>main.py</em></p><pre>import os<br>from dotenv import load_dotenv<br>from customersreport.quickbooks_client import QuickbooksClient<br><br>load_dotenv()<br><br>def main():<br>    quickbooks_client = QuickbooksClient(<br>        base_url=os.environ.get(&quot;QUICKBOOKS_BASE_URL&quot;),<br>        company_id=os.environ.get(&quot;QUICKBOOKS_COMPANY_ID&quot;),<br>        access_token=os.environ.get(&quot;QUICKBOOKS_ACCESS_TOKEN&quot;)<br>    )<br>    print(quickbooks_client.load_invoices())<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Running this project with the following command, if everything is correctly configured, should log the invoices issued by the company:</p><pre>python main.py<br><br># On some operating systems, the Python interpreter binary might be named python3, so the command should be as follows:<br>python3 main.py</pre><p>Resulting invoices are:</p><pre>python3 main.py <br>{&#39;QueryResponse&#39;: {&#39;Invoice&#39;: [{&#39;AllowIPNPayment&#39;: False, &#39;AllowOnlinePayment&#39;: False, &#39;AllowOnlineCreditCardPayment&#39;: False, &#39;AllowOnlineACHPayment&#39;: False, &#39;domain&#39;: &#39;QBO&#39;, &#39;sparse&#39;: False, &#39;Id&#39;: &#39;146&#39;, &#39;SyncToken&#39;: &#39;0&#39;, &#39;MetaData&#39;: {&#39;CreateTime&#39;: &#39;2025-01-09T01:40:36-08:00&#39;, &#39;LastUpdatedTime&#39;: &#39;2025-01-09T01:40:36-08:00&#39;}, &#39;CustomField&#39;: [], &#39;DocNumber&#39;: &#39;1039&#39;, &#39;TxnDate&#39;: &#39;2025-01-09&#39;, &#39;CurrencyRef&#39;: {&#39;value&#39;: &#39;EUR&#39;, &#39;name&#39;: &#39;Euro&#39;}, &#39;ExchangeRate&#39;: 1.02941, &#39;LinkedTxn&#39;: [], &#39;Line&#39;: [{&#39;Id&#39;: &#39;1&#39;, &#39;LineNum&#39;: 1, &#39;Description&#39;: &#39;Weekly Gardening Service&#39;, &#39;Amount&#39;: 1000.0, &#39;DetailType&#39;: &#39;SalesItemLineDetail&#39;, &#39;SalesItemLineDetail&#39;: {&#39;ItemRef&#39;: {&#39;value&#39;: &#39;6&#39;, &#39;name&#39;: &#39;Gardening&#39;}, &#39;UnitPrice&#39;: 100, &#39;Qty&#39;: 10, &#39;TaxCodeRef&#39;: {&#39;value&#39;: &#39;NON&#39;}}}, {&#39;Amount&#39;: 1000.0, &#39;DetailType&#39;: &#39;SubTotalLineDetail&#39;, &#39;SubTotalLineDetail&#39;: {}}], &#39;TxnTaxDetail&#39;: {&#39;TotalTax&#39;: 0}, &#39;CustomerRef&#39;: {&#39;value&#39;: &#39;58&#39;, &#39;name&#39;: &#39;Mr Abc Bcd Cde&#39;}, &#39;CustomerMemo&#39;: {&#39;value&#39;: &#39;Thank you for your business and have a great day!&#39;}, &#39;BillAddr&#39;: {&#39;Id&#39;: &#39;96&#39;, &#39;City&#39;: &#39;Berlin&#39;, &#39;Country&#39;: &#39;Germany&#39;}, &#39;ShipAddr&#39;: {&#39;Id&#39;: &#39;96&#39;, &#39;City&#39;: &#39;Berlin&#39;, &#39;Country&#39;: &#39;Germany&#39;}, &#39;SalesTermRef&#39;: {&#39;value&#39;: &#39;3&#39;, &#39;name&#39;: &#39;Net 30&#39;}, &#39;DueDate&#39;: &#39;2025-02-08&#39;, &#39;TotalAmt&#39;: 1000.0, &#39;HomeTotalAmt&#39;: 1029.41, &#39;ApplyTaxAfterDiscount&#39;: False, &#39;PrintStatus...</pre><h4>8. Completing Project File Structure</h4><p>Having built the necessary modules to successfully communicate with the API, we can now focus on the specific goal of this project: creating a customer report with customers sorted by their monthly average revenue contribution to the company. The report will be generated as a PDF and saved to the filesystem.</p><p>To achieve this, the following two classes are created:</p><ul><li>PdfReportBuilder: This class generates the final PDF report based on the provided data.</li><li>CustomersReport: This class uses the QuickBooksClient to retrieve the necessary data, processes and formats it, and prepares it for the PdfReportBuilder.</li></ul><p>The basic code stubs for these classes are as follows:</p><p><em>customersreport/pdf_report_builder.py</em></p><pre>import os<br>from fpdf import FPDF<br><br>class PdfReportBuilder:<br>    def create_report(self, file_name, data):<br>        cwd = os.getcwd()<br>        report_path = os.path.join(cwd, &quot;reports&quot;)<br><br>        fpdf = FPDF()<br>        fpdf.add_page()<br>        fpdf.set_font(&quot;Arial&quot;, size=12)<br>        fpdf.text(25, 25, &quot;Test Content!&quot;)<br>        fpdf.output(f&quot;{report_path}/{file_name}.pdf&quot;)</pre><p><em>customersreport/customers_report.py</em></p><pre>import os<br><br>from customersreport.pdf_report_builder import PdfReportBuilder<br>from customersreport.quickbooks_client import QuickbooksClient<br><br>class CustomersReport:<br>    def __init__(self):<br>        self.quickbooks_client = QuickbooksClient(<br>            base_url=os.environ.get(&quot;QUICKBOOKS_BASE_URL&quot;),<br>            company_id=os.environ.get(&quot;QUICKBOOKS_COMPANY_ID&quot;),<br>            access_token=os.environ.get(&quot;QUICKBOOKS_ACCESS_TOKEN&quot;)<br>        )<br><br>        self.pdf_report_builder = PdfReportBuilder()<br><br>    def get_customers_report(self):<br>        self.pdf_report_builder.create_report(&quot;Test-File&quot;, [])</pre><p>And to ensure that the CustomersReport class serves as the entry point, the content of main.py has also been updated.</p><p><em>main.py</em></p><pre>from dotenv import load_dotenv<br><br>from customersreport.customers_report import CustomersReport<br><br>load_dotenv()<br><br>def main():<br>    customers_report = CustomersReport()<br>    customers_report.get_customers_report()<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>In line with our intent to save reports on the file system, we should create a new directory named “reports” in the root of the project. This directory should be included in .gitignore, as it will be used to store the resulting PDF reports that should not be tracked trough git with other environments.</p><p>We should save a .gitkeep file inside the reports directory, and this file should be tracked by Git. The purpose of this is to ensure that the reports directory is delivered through Git, but without any actual report files.</p><p><em>.gitignore</em></p><pre>.idea<br>.env<br>reports/*<br>!reports/.gitkeep</pre><p>The finalized code structure for this project is outlined in the dependency graph shown in the following illustration.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*g13mqRAXYDh5sfyE" /></figure><h4>9. Customer’s Report</h4><p>Having API tested, development structure defined, it is time for final implementation of customer’s report data. By our plan, we need to extend our QuickbooksClient class, to perform all necessary fetching API calls.</p><p><em>customersreport/quickbooks_client.py</em></p><pre>import requests<br><br>class QuickbooksClient:<br>    def __init__(self, base_url, company_id, access_token):<br>        self.access_token = access_token<br>        self.base_url = base_url<br>        self.company_id = company_id<br><br>    def get_invoices_count(self):<br>        url = f&quot;{self.base_url}/v3/company/{self.company_id}/query&quot;<br>        params = {<br>            &#39;query&#39;: &#39;select count(*) from Invoice&#39;<br>        }<br><br>        return self.do_request(url, params)<br><br>    def load_invoices(self, page_size, start_position):<br>        url = f&quot;{self.base_url}/v3/company/{self.company_id}/query&quot;<br>        params = {<br>            &#39;query&#39;: f&quot;select * from Invoice maxResults {page_size} startPosition {start_position}&quot;<br>        }<br><br>        return self.do_request(url, params)<br><br>    def get_customer_data(self, customer_ids):<br>        url = f&quot;{self.base_url}/v3/company/{self.company_id}/query&quot;<br><br>        ids_query = &quot;(&quot; + &quot;, &quot;.join([f&quot;&#39;{customer_id}&#39;&quot; for customer_id in customer_ids]) + &quot;)&quot;<br><br>        params = {<br>            &quot;query&quot;: f&quot;select * from Customer where id IN {ids_query}&quot;<br>        }<br><br>        return self.do_request(url, params)<br><br>    def do_request(self, url, params):<br>        try:<br>            response = requests.get(<br>                url,<br>                headers={<br>                    &#39;Accept&#39;: &#39;application/json&#39;,<br>                    &#39;Authorization&#39;: f&#39;Bearer {self.access_token}&#39;<br>                },<br>                params=params<br>            )<br>            response_json = response.json()<br>            return response_json<br><br>        except requests.exceptions.RequestException as e:<br>            print(&#39;Error:&#39;, e)<br>            return None</pre><p>With QuickbooksClient ready, implementation of data processing layer is in place. To remind, this class is supposed to prepare data for PDF report.</p><p><em>customersreport/customers_report.py</em></p><pre>import datetime<br>import os<br><br>from customersreport.pdf_report_builder import PdfReportBuilder<br>from customersreport.quickbooks_client import QuickbooksClient<br><br>class CustomersReport:<br>    def __init__(self):<br>        self.quickbooks_client = QuickbooksClient(<br>            base_url=os.environ.get(&quot;QUICKBOOKS_BASE_URL&quot;),<br>            company_id=os.environ.get(&quot;QUICKBOOKS_COMPANY_ID&quot;),<br>            access_token=os.environ.get(&quot;QUICKBOOKS_ACCESS_TOKEN&quot;)<br>        )<br><br>        self.pdf_report_builder = PdfReportBuilder()<br><br>    def get_customers_report(self):<br>        report_data = self.prepare_customer_report_data()<br>        self.pdf_report_builder.create_report(datetime.datetime.today(), report_data)<br><br>    def prepare_customer_report_data(self):<br>        invoices = self.get_all_invoices()<br>        customers = self.group_invoices_by_customers(invoices)<br>        self.calculate_customer_revenue_averages(customers)<br>        self.update_customers_informative_data(customers)<br>        report_data = self.map_to_report_data(customers)<br><br>        return report_data<br><br>    def get_all_invoices(self):<br>        invoices = []<br><br>        invoice_count_response = self.quickbooks_client.get_invoices_count()<br>        invoice_count = invoice_count_response[&quot;QueryResponse&quot;][&quot;totalCount&quot;]<br><br>        page_size = 50<br>        for i in range(1, invoice_count, page_size):<br>            invoices_page_response = self.quickbooks_client.load_invoices(page_size, i)<br>            invoices += invoices_page_response[&quot;QueryResponse&quot;][&quot;Invoice&quot;]<br><br>        return invoices<br><br>    def group_invoices_by_customers(self, invoices):<br>        customers = {}<br><br>        for invoice in invoices:<br>            customer_id = invoice[&quot;CustomerRef&quot;][&quot;value&quot;]<br>            if customer_id not in customers:<br>                customers[customer_id] = {<br>                    &quot;id&quot;: customer_id,<br>                    &quot;invoices&quot;: []<br>                }<br><br>            customers[customer_id][&quot;invoices&quot;].append(invoice)<br><br>        return [customers[key] for key in customers.keys()]<br><br>    def diff_month(self, d1, d2):<br>        return (d1.year - d2.year) * 12 + d1.month - d2.month<br><br>    def calculate_customer_revenue_averages(self, customers):<br>        for customer in customers:<br>            revenue = 0<br>            invoices = customer[&quot;invoices&quot;]<br><br>            earliest_invoice_date = datetime.date.fromisoformat(invoices[0][&quot;DueDate&quot;])<br>            latest_invoice_date = datetime.date.fromisoformat(invoices[0][&quot;DueDate&quot;])<br><br>            for invoice in invoices:<br>                invoice_date = datetime.date.fromisoformat(invoice[&quot;DueDate&quot;])<br><br>                if &quot;HomeTotalAmt&quot; in invoice:<br>                    revenue += invoice[&quot;HomeTotalAmt&quot;]<br>                else:<br>                    revenue += invoice[&quot;TotalAmt&quot;]<br><br>                if earliest_invoice_date &gt; invoice_date:<br>                    earliest_invoice_date = invoice_date<br>                elif latest_invoice_date &lt; invoice_date:<br>                    latest_invoice_date = invoice_date<br><br>            cooperation_months = self.diff_month(latest_invoice_date, earliest_invoice_date) + 1<br>            customer[&quot;averageRevenue&quot;] = revenue / cooperation_months<br><br>        customers.sort(key=lambda cust: cust[&quot;averageRevenue&quot;], reverse=True)<br><br>    def update_customers_informative_data(self, customers):<br>        customer_ids = [customer[&quot;id&quot;] for customer in customers]<br>        customer_api_data_response = self.quickbooks_client.get_customer_data(customer_ids)<br>        customer_api_data = customer_api_data_response[&quot;QueryResponse&quot;][&quot;Customer&quot;]<br><br>        for customer in customers:<br>            customer[&quot;details&quot;] = {}<br><br>            customer_info = next(c for c in customer_api_data if c[&quot;Id&quot;] == customer[&quot;id&quot;])<br><br>            if &quot;CompanyName&quot; in customer_info:<br>                customer[&quot;details&quot;][&quot;isCompany&quot;] = True<br>            else:<br>                customer[&quot;details&quot;][&quot;isCompany&quot;] = False<br><br>            customer[&quot;details&quot;][&quot;name&quot;] = customer_info[&quot;FullyQualifiedName&quot;]<br>            customer[&quot;details&quot;][&quot;address&quot;] = customer_info[&quot;BillAddr&quot;]<br><br>    def map_to_report_data(self, customers):<br>        return [self.map_single_customer(customer) for customer in customers]<br><br>    def map_single_customer(self, customer):<br>        report_item = {<br>            &quot;name&quot;: customer[&quot;details&quot;][&quot;name&quot;],<br>            &quot;address&quot;: customer[&quot;details&quot;][&quot;address&quot;],<br>            &quot;is_company&quot;: customer[&quot;details&quot;][&quot;isCompany&quot;],<br>            &quot;revenue_average&quot;: customer[&quot;averageRevenue&quot;],<br>            &quot;invoices_count&quot;: len(customer[&quot;invoices&quot;])<br>        }<br><br>        return report_item</pre><p>As the result of processing, report data is as follows:</p><pre>[{<br>    &#39;name&#39;: &#39;Cool Cars&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;4&#39;,<br>        &#39;Line1&#39;: &#39;65 Ocean Dr.&#39;,<br>        &#39;City&#39;: &#39;Half Moon Bay&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;CA&#39;,<br>        &#39;PostalCode&#39;: &#39;94213&#39;,<br>        &#39;Lat&#39;: &#39;37.4300318&#39;,<br>        &#39;Long&#39;: &#39;-122.4336537&#39;<br>    },<br>    &#39;is_company&#39;: True,<br>    &#39;revenue_average&#39;: 2369.52,<br>    &#39;invoices_count&#39;: 1<br>}, {<br>    &#39;name&#39;: &#39;Mr Abc Bcd Cde&#39;,<br>    &#39;address&#39;: {&#39;Id&#39;: &#39;96&#39;, &#39;City&#39;: &#39;Berlin&#39;, &#39;Country&#39;: &#39;Germany&#39;},<br>    &#39;is_company&#39;: True,<br>    &#39;revenue_average&#39;: 1029.41,<br>    &#39;invoices_count&#39;: 1<br>}, {<br>    &#39;name&#39;: &#39;Paulsen Medical Supplies&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;18&#39;,<br>        &#39;Line1&#39;: &#39;900 Main St.&#39;,<br>        &#39;City&#39;: &#39;Middlefield&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;CA&#39;,<br>        &#39;PostalCode&#39;: &#39;94303&#39;,<br>        &#39;Lat&#39;: &#39;37.445013&#39;,<br>        &#39;Long&#39;: &#39;-122.1391443&#39;<br>    },<br>    &#39;is_company&#39;: True,<br>    &#39;revenue_average&#39;: 954.75,<br>    &#39;invoices_count&#39;: 1<br>}, {<br>    &#39;name&#39;: &#39;John Melton&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;13&#39;,<br>        &#39;Line1&#39;: &#39;85 Pine St.&#39;,<br>        &#39;City&#39;: &#39;Menlo Park&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;CA&#39;,<br>        &#39;PostalCode&#39;: &#39;94304&#39;,<br>        &#39;Lat&#39;: &#39;37.4451342&#39;,<br>        &#39;Long&#39;: &#39;-122.1409626&#39;<br>    },<br>    &#39;is_company&#39;: False,<br>    &#39;revenue_average&#39;: 750.0,<br>    &#39;invoices_count&#39;: 1<br>},<br>...<br>{<br>    &#39;name&#39;: &#39;Travis Waldron&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;27&#39;,<br>        &#39;Line1&#39;: &#39;78 First St.&#39;,<br>        &#39;City&#39;: &#39;Monlo Park&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;CA&#39;,<br>        &#39;PostalCode&#39;: &#39;94304&#39;,<br>        &#39;Lat&#39;: &#39;37.4585825&#39;,<br>        &#39;Long&#39;: &#39;-122.1352789&#39;<br>    },<br>    &#39;is_company&#39;: False,<br>    &#39;revenue_average&#39;: 599.27,<br>    &#39;invoices_count&#39;: 3<br>}, {<br>    &#39;name&#39;: &#39;Dukes Basketball Camp&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;6&#39;,<br>        &#39;Line1&#39;: &#39;25 Court St.&#39;,<br>        &#39;City&#39;: &#39;Tucson&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;AZ&#39;,<br>        &#39;PostalCode&#39;: &#39;85719&#39;,<br>        &#39;Lat&#39;: &#39;32.2841116&#39;,<br>        &#39;Long&#39;: &#39;-110.9744298&#39;<br>    },<br>    &#39;is_company&#39;: True,<br>    &#39;revenue_average&#39;: 490.1,<br>    &#39;invoices_count&#39;: 2<br>},,<br>...<br>{<br>    &#39;name&#39;: &#39;Freeman Sporting Goods:55 Twin Lane&#39;,<br>    &#39;address&#39;: {<br>        &#39;Id&#39;: &#39;9&#39;,<br>        &#39;Line1&#39;: &#39;370 Easy St.&#39;,<br>        &#39;City&#39;: &#39;Middlefield&#39;,<br>        &#39;CountrySubDivisionCode&#39;: &#39;CA&#39;,<br>        &#39;PostalCode&#39;: &#39;94482&#39;,<br>        &#39;Lat&#39;: &#39;37.4031672&#39;,<br>        &#39;Long&#39;: &#39;-122.0642815&#39;<br>    },<br>    &#39;is_company&#39;: True,<br>    &#39;revenue_average&#39;: 73.8,<br>    &#39;invoices_count&#39;: 3<br>}]</pre><h4>10. PDF Report Builder</h4><p>As the final step, we need to implement the PDF Report Builder so that we can successfully build a PDF document with the results of our calculations.</p><p><em>customersreport/pdf_report_builder.py</em></p><pre>import os<br>from fpdf import FPDF<br><br>class PdfReportBuilder:<br>    def create_report(self, file_name, data):<br>        cwd = os.getcwd()<br>        report_path = os.path.join(cwd, &quot;reports&quot;)<br><br>        fpdf = FPDF(orientation=&#39;L&#39;)<br>        fpdf.add_page()<br>        fpdf.set_font(&quot;Arial&quot;, size=12)<br><br>        cell_height = fpdf.font_size * 3<br>        fpdf.cell(fpdf.w, cell_height,<br>                  txt=&quot;Customers Report by Monthly Average Revenue&quot;)<br>        fpdf.ln(cell_height)<br><br>        self.build_table(fpdf, data)<br><br>        fpdf.output(f&quot;{report_path}/{file_name}.pdf&quot;)<br><br>    def build_table(self, fpdf, data):<br>        records = [<br>            [&#39;Name&#39;, &#39;Address&#39;, &#39;Company?&#39;, &#39;Monthly Revenue Average&#39;, &#39;Invoices&#39;]<br>        ]<br><br>        for item in data:<br>            record = []<br>            record.append(item[&#39;name&#39;])<br>            address = item[&#39;address&#39;]<br>            record.append(self.build_address_line(address))<br>            record.append(&#39;Yes&#39; if item[&#39;is_company&#39;] else &#39;No&#39;)<br>            record.append(f&quot;{item[&#39;revenue_average&#39;]:.2f}&quot;)<br>            record.append(f&quot;{item[&#39;invoices_count&#39;]}&quot;)<br><br>            for i, val in enumerate(record):<br>                record[i] = f&quot;{val[0: 20]}...&quot; if len(val) &gt; 23 else val<br><br>            records.append(record)<br><br>        col_width = fpdf.w / (len(records[0]) + 0.5)<br>        row_height = fpdf.font_size<br>        spacing = 3<br><br>        for row in records:<br>            for item in row:<br>                fpdf.cell(col_width, row_height * spacing,<br>                         txt=item, border=1, )<br>            fpdf.ln(row_height * spacing)<br><br>    def build_address_line(self, address):<br>        keys = [&#39;Line1&#39;, &#39;City&#39;, &#39;PostalCode&#39;, &#39;CountrySubDivisionCode&#39;]<br><br>        result = []<br>        for key in keys:<br>            if key in address:<br>                result.append(address[key])<br><br>        return &#39;, &#39;.join(result)</pre><p>Resulting report from this code is:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*RjmSbpBjHYKFv74q" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*CyRuw44I-8zcfJ_i" /></figure><h4>11. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next QuickBooks or Python project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e5dbd458e1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 4] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?]]></title>
            <link>https://medium.com/@emir_75658/part-4-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose-6440ef6b4a7c?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6440ef6b4a7c</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[web-rendering]]></category>
            <category><![CDATA[hot-wires]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 15:37:10 GMT</pubDate>
            <atom:updated>2025-01-08T15:37:10.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Part 4] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?</h3><h4>After analyzing HTML (server-side) rendering in [Part 1], JavaScript (client-side) rendering in [Part 2], and Hotwire rendering in [Part 3], we are finally examining how to make a choice. What might be the main criteria for this decision, and what are the consequences of the choice made?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*RZa2REv-86ysmRt6" /></figure><h4>1. Article parts</h4><p>To tackle the topic of web application interface (GUI) rendering and to compare available approaches, the article is split into following parts:</p><ul><li><a href="https://blog.gradient.ba/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">HTML and HTML partials rendering [Part 1]</a>,</li><li><a href="https://blog.gradient.ba/part-2-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">Javascript rendering [Part 2]</a><strong>,</strong></li><li><a href="https://blog.gradient.ba/part-3-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">Hotwire [Part 3]</a>,</li><li><strong>Conceptual differences of all approaches and how to choose [This part]</strong>.</li></ul><h4>2. Different Perspectives</h4><p>As with any general business or technical problem, there is no single clear-cut solution, and web GUI rendering is no exception. The best choice is determined by considering different perspectives, with the solution that best satisfies all of them emerging as the winner.</p><p>In this article, the following perspectives are analyzed, and a solution is chosen based on them:</p><ul><li>GUI Dynamics</li><li>Development Efficiency</li><li>Rendered Elements Complexity</li><li>Real-Time Aspects</li></ul><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*xswdp9UrtJiA2cCd" /></figure><h4>3. GUI Dynamics</h4><p>The first relevant perspective to consider is whether the expected user interface is static or dynamic.</p><p>Static GUI refers to a web interface that does not change due to user interaction or external factors. In this context, the page loaded for the end-user remains unchanged during their usage of that page. A common interaction that still falls under the static GUI category is when a user’s action redirects them to another page, such as clicking on a navigation bar or submitting a form via an action button or link.</p><p>It’s important not to confuse static or dynamic GUI with static or dynamic web applications. A dynamic web application generates different content based on various factors. For example, a blog where each post has unique content sourced from a database would be considered dynamic. However, from the GUI perspective, the post page itself is largely static, as the interface remains unchanged during the user’s interaction with a specific article. Exceptions might include interactive elements like search and navigation buttons, which are dynamic.</p><p>Dynamic GUI, on the other hand, refers to interfaces where multiple small portions or larger sections (partials) of the page change based on user interactions. For example, in an invoicing application, the user might fill in customer details, select an invoice type, set a payment due date, or add and remove invoice items. Each of these actions triggers dynamic behavior in the interface, such as recalculating totals, applying taxes, and validating rules for invoice creation. For instance, adding or removing invoice items updates the total amount, while selecting a different currency adjusts the exchange rates accordingly. In this scenario, nearly every interaction on the invoice page causes one or more elements of the interface to update dynamically.</p><p>Choices:</p><ul><li>For mainly static GUI pages, HTML (server-side rendering) is the most reasonable choice. The system operates such that every user interaction prompts the web server to respond with a new page to be presented.</li><li>For GUI pages that are dynamic in the sense that significant but independent parts change (e.g., a “wall” on social networks), a reasonable approach is dynamic partial rendering. One option covered in this article is Hotwire.</li><li>For dynamic GUI pages where user interactions primarily affect multiple elements across the interface, single-page application (SPA) frameworks are a more suitable choice. One option discussed in this article is React.</li></ul><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*mkH1J1g5DEty6uJp" /></figure><h4>4. Development Efficiency</h4><p>The development efficiency perspective is a critical factor to consider. The complexity of GUI requirements in a project significantly influences the suitability of available approaches, making some choices simpler or more complex. Each approach discussed in this article spans the spectrum from “very simple” to “very complex,” depending on the specific GUI requirements.</p><p>For example, static GUI pages are easiest to implement using HTML (server-side) rendering. Conversely, implementing highly complex dynamic GUI pages with HTML rendering is the most challenging option.</p><p>When the requirements fall between these extremes — where independent partials are updated (not a purely static GUI), but user interactions do not affect multiple parts of the interface (not a highly dynamic GUI) — Hotwire emerges as the best choice. In such scenarios, development is relatively straightforward with Hotwire, while the other two approaches, HTML rendering and Single Page Application (SPA) rendering, result in a medium level of complexity.</p><h4>5. Rendered Elements Complexity</h4><p>An important perspective to consider is the requirement to render one or more visually complex elements that need to be updated due to external factors or user interactions. Such elements typically involve usage history, where past interactions influence the current state. Examples include schematic designs, custom configurable dashboards, or similar components. In these cases, each update often involves adding new elements, making every re-render progressively more complex.</p><p>For such scenarios, the best approach among the three considered in this article is Single Page Application (SPA) rendering. With SPA rendering, the interface is loaded once and subsequently updated incrementally with additional data, avoiding the need to re-render the entire element.</p><p>The next best option would be partials rendering using Hotwire modules, provided the additional or updated elements are designed as independent parts (partials). This approach ensures only the necessary sections are updated, reducing the rendering workload compared to reloading entire components.</p><p>The least effective approach is HTML (server-side) rendering, where the entire interface is re-rendered from scratch with each interaction.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*q6kMVrRlAArOIBWg" /></figure><h4>6. Real-Time Aspects</h4><p>The final perspective considered here involves real-time aspects of the requirements. Real-time updates occur when the interface must be updated within a specified time span following one or more external events. The choice of rendering approach depends on the allowed time span and the complexity of the required visualization.</p><p>For scenarios with longer time spans (e.g., updates once per hour or half-hour for slowly changing values like weather temperature), both HTML (server-side rendering) and Hotwire rendering are suitable options. These approaches can handle periodic updates efficiently, as the frequency and complexity of the updates do not demand rapid or continuous rendering.</p><p>In contrast, for high-speed scenarios requiring updates in milliseconds — such as stock or cryptocurrency market tracking — Single Page Applications (SPAs) are the best choice from the three. SPAs enable charts, order books, trade lists, and user-specific data to be rendered during the initial load, with subsequent updates handled incrementally as new information arrives. This approach ensures the interface remains responsive and up-to-date in real-time without requiring a complete re-render.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*UPfQKWmlSABFH-Wx" /></figure><h4>7. So, What’s the Best Choice?</h4><p>Having considered all these perspectives, it becomes clear that the choice of rendering approach depends on the specific requirements. The good news is that some scenarios lead to very clear-cut decisions:</p><ul><li>If the GUI is mainly visually static, choose HTML rendering.</li><li>If the GUI is moderately dynamic, with separate partials to be updated, use Hotwire.</li><li>If the requirement involves one or more visually complex elements that need to be rendered and updated based on user interactions or external events, opt for a Single Page Application (SPA) approach.</li><li>If there is a real-time aspect with a very short time span for updates, use the SPA approach.</li></ul><p>For requirements that do not fall into these clear-cut categories, deeper analysis is needed. In such cases, development efficiency becomes a key consideration. Throughout the previous parts of this article (Parts 1 to 3), we’ve discussed the complexity of each approach when they are used to satisfy specific requirements:</p><ul><li>The simplest to implement is HTML rendering (see Part 1).</li><li>Hotwire rendering is slightly more complex (see Part 3).</li><li>The most complex is JavaScript rendering using Single Page Applications (see Part 2).</li></ul><p>Based on the perspectives shared in this article, the decision-making process should follow these steps:</p><ul><li>If HTML rendering satisfies the requirement, it is the reasonable choice. If not:</li><li>If Hotwire rendering satisfies the requirement, it is the reasonable choice. If not:</li><li>Choose Single Page Application rendering as the reasonable choice.</li></ul><p>In summary: “Choose the least complex approach that satisfies the requirement.”</p><p>It’s important to note that these approaches are not mutually exclusive. Within an application that primarily uses HTML rendering, certain parts can be implemented with partial rendering or even behave like SPA-rendered elements. Similarly, the reverse is also possible. However, such adaptations are often impractical and not scalable, so we want to keep them as small part of our project.</p><p>So, if the application GUI is almost entirely static, with only a small part requiring SPA-like behavior, it is better to choose HTML rendering and use JavaScript to handle the dynamic section (SPA or Hotwire). In cases of uncertainty, favor the more complex option from the list. The reasoning is straightforward: it is easier to create a static page in Hotwire or SPA framework than to build a dynamic component in HTML and JavaScript.</p><h4>8. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next Web project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6440ef6b4a7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 3] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?]]></title>
            <link>https://medium.com/@emir_75658/part-3-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose-0abf87ba2336?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0abf87ba2336</guid>
            <category><![CDATA[turbo-stream]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[turbo-frame]]></category>
            <category><![CDATA[hot-wires]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 15:36:40 GMT</pubDate>
            <atom:updated>2025-01-08T15:36:40.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Part 3] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?</h3><h4>After the analysis of HTML (server side) rendering in the [Part 1], and Javascript (client side) rendering in the [Part 2], we are focusing on one “hybrid” idea in this article. In this approach, we are utilizing Hotwire Turbo to take care of GUI rendering. We do utilize minimal Javascript in this approach, and partials rendering is still on the server side. Hotwire Turbo provides us with “all in one” Javascript bundle that autonomously communicates with server and updates GUI as required.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*B9ZvYwlTMilGoOVl" /></figure><h4>1. Article parts</h4><p>To tackle the topic of web application interface (GUI) rendering and to compare available approaches, the article is split into following parts:</p><ul><li><a href="https://blog.gradient.ba/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">HTML and HTML partials rendering [Part 1]</a>,</li><li><a href="https://blog.gradient.ba/part-2-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">Javascript rendering [Part 2]</a><strong>,</strong></li><li><strong>Hotwire [This part],</strong></li><li><a href="https://blog.gradient.ba/part-4-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">Conceptual differences of all approaches and how to choose [Part 4]</a></li></ul><h4>2. GitHub Repository</h4><p>There is one solution presented in this article and complete implementation of solution shown in this article can be cloned from GitHub repository: <a href="https://github.com/Gradient-s-p/express-hotwire-rendering">https://github.com/Gradient-s-p/express-hotwire-rendering</a>.</p><h4>3. Hotwire Turbo</h4><p>Hotwire Turbo is one toolkit provided to us by <a href="https://37signals.com/">37signals</a>. About all provided Hotwire toolkits, one can read <a href="https://hotwired.dev/">here</a>.</p><p><strong>Turbo</strong> module is installed as external Javascript reference in HTML of the Web application. This module intercepts http requests that would be by default performed in browser (hyperlink clicks and form submits) and performs Web Socket communication with the server. Also, only parts of the interface (controlled by server) are delivered to client and replaced by Turbo.</p><p>Full idea is to have hybrid behavior that semantically fits between server-side HTML rendering and client-side Javascript rendering in a way that initial page load is delivered as final HTML, but every change/interaction on the interface is done with Javascript.</p><p>More on the positive and negative sides of these approaches will be written in [Part 4] of this article.</p><h4>4. Greeting App</h4><p>Throughout all three parts of this article we are implementing the same Greeting App utilizing different technologies and rendering methods. This part is not exception.</p><p>If we check the result of <a href="https://blog.gradient.ba/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">[Part 1]</a> of this article, there is Greeting App with partials rendering developed (and can be cloned from GitHub repository shared in that article). In the [Part 1], we have incorporated our own relatively small and relatively simple JavaScript implementation that intercepts link clicks and form submits. Mentioned implementation was written for the Greeting App explicitly, and will not work correctly for general usage on other applications.</p><p>For the purpose of Hotwire Turbo integration, we will start with that application, and perform step by step process to replace that Javascript partials rendering solution with Hotwire Turbo.</p><h4>5. Removing the JavaScript partials replacement solution</h4><p>File <em>public/example-application.js </em>consists of our partials replacement solution. So, we start by removing it from the source code.</p><p>This JavaScript solution is also referenced from <em>views/partials/footer.ejs </em>view file. We remove that reference also. After that, <em>footer.ejs </em>file looks as follows:</p><p><em>views/partials/footer.ejs</em></p><pre>&lt;%- include(&#39;navbar&#39;, { navItems: [<br>    {<br>       path: &#39;/partial-home&#39;,<br>       title: &#39;Home&#39;<br>    },<br>    {<br>       path: &#39;/partial-greet&#39;,<br>       title: &#39;Default Greet&#39;<br>    },<br>    {<br>       path: &#39;/partial-add-name&#39;,<br>       title: &#39;Add Name&#39;<br>    }<br>] }); %&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>If we, after these removals, start our server we see that home page works correctly, but partials are rendered as new pages (instead of being replaced into ‘main-area’). JavaScript module that we removed has been utilized for that.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*s_kaJLMpwE0-oFrs" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*0eBWrBUrqjAgP88e" /></figure><h4>6. Including Hotwire Turbo</h4><p>There are multiple ways to integrate Hotwire Turbo to our web application. In this example, we use installation from npm registry.</p><p>We install “@hotwired/turbo” as a dependency using following command in the root of the project:</p><pre>yarn add @hotwired/turbo</pre><p>After successful installation, client script is saved in <em>node_modules/@hotwired/turbo/dist/turbo.es2017-umd.js</em>. There are multiple viable approaches to deliver this script from the server. In this article, approach where server statically serves <em>turbo.es2017-umd.js</em> directly from <em>node_modules</em> is utilized.</p><p>So, we extend our server implementation with the following changes:</p><p><em>src/index.js</em></p><pre>const express = require(&#39;express&#39;);<br>const path = require(&#39;path&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br>app.use(express.static(&#39;public&#39;));<br><br>app.get(&#39;/turbo.es2017-umd.js&#39;, (req, res) =&gt; {<br>  const turboLibPath = path.join(process.cwd(), &quot;node_modules/@hotwired/turbo/dist/turbo.es2017-umd.js&quot;);<br>  res.sendFile(turboLibPath);<br>});<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.render(&#39;home&#39;);<br>});<br><br>// Rest of the implementation</pre><p><em>views/partials/header.ejs</em></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en-US&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;/example-application.css&quot;&gt;<br><br>    &lt;script src=&quot;/turbo.es2017-umd.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><p>After starting our server, we can notice that home page looks exactly the same. But when we click on any of navigation links, styles are preserved because complete HTML &lt;body&gt; is replaced, but not style part. Also, if we analyze through Network Tab in browser (Inspect/Developer Console) we can notice that http requests towards server are XHR ones initiated from <em>turbo.es2917-umd.js</em>, meaning that all link clicks are intercepted by Turbo implementation that we just included.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*eFh9aoNmHdLQKCFB" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*tCl9MKDnSzUjG2Xy" /></figure><h4>7. Optimizing Responses by Including Only Necessary Partials</h4><p>Currently, our system renders the entire page on every HTTP request, a legacy from the earlier Express version built in <a href="https://medium.com/part-2-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">[Part 2]</a>. Our goal is to replace only the main area of the application. To begin, we need to define the main area.</p><p><em>views/home.ejs</em></p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_home&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p><em>views/partials/_home.ejs</em></p><pre>&lt;turbo-stream action=&quot;update&quot; target=&quot;main-area&quot;&gt;<br>    &lt;template&gt;<br>            &lt;h1&gt;Example Project Body&lt;/h1&gt;<br>    &lt;/template&gt;<br>&lt;/turbo-stream&gt;</pre><p>Let’s explain the components of<em> views/partials/_home.ejs</em> part by part:</p><ul><li>&lt;turbo-stream /&gt; tag — This tag in the response informs the underlying TurboStream JavaScript implementation that this statement is meant for it.</li><li>action=”update” — This attribute tells TurboStream to perform an update.</li><li>target=”main-area” — This attribute specifies which element on the interface should be replaced.</li><li>&lt;template /&gt; tag — This tag defines the template containing the content that will be used for the replacement.</li></ul><p>This response instructs: “Replace the content of the element with the id ‘main-area’ with the following provided template.”</p><p>We apply the same incorporation with the other templates.</p><p><em>views/greet.ejs</em></p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Greeting Example&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_greet&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p><em>views/add-name.ejs</em></p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_add-name&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p><em>views/partials/_greet.ejs</em></p><pre>&lt;turbo-stream action=&quot;update&quot; target=&quot;main-area&quot;&gt;<br>    &lt;template&gt;<br>        &lt;h1&gt;&lt;%= message %&gt;&lt;/h1&gt;<br>    &lt;/template&gt;<br>&lt;/turbo-stream&gt;</pre><p><em>views/partials/_add-name.ejs</em></p><pre>&lt;turbo-stream action=&quot;update&quot; target=&quot;main-area&quot;&gt;<br>    &lt;template&gt;<br>        &lt;h1&gt;Add your name:&lt;/h1&gt;<br>        &lt;form method=&quot;get&quot; action=&quot;/partial-greet&quot;&gt;<br>            &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>            &lt;input id=&quot;name&quot; type=&quot;text&quot; name=&quot;name&quot;&gt;<br><br>            &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/form&gt;<br>    &lt;/template&gt;<br>&lt;/turbo-stream&gt;</pre><p>And finally, server related to delivering main (initial) pages for three endpoints looks as follows:</p><p><em>src/index.js</em></p><pre>// Rest of the implementation<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.render(&#39;home&#39;);<br>});<br><br>app.get(&#39;/greet&#39;, (req, res) =&gt; {<br>  const name = req.query.name ? req.query.name : null;<br>  const message = name ? `Hello ${name}!` : `Hello!`;<br><br>  res.render(&#39;greet&#39;, {<br>    message<br>  });<br>});<br><br>app.get(&#39;/add-name&#39;, (req, res) =&gt; {<br>  res.render(&#39;add-name&#39;);<br>});<br><br>// Rest of the implementation</pre><p>With partials prepared using TurboStream instructions, the only remaining requirement is for the server to respond with the appropriate partials in the correct HTTP content type. The implementation is as follows.</p><p><em>src/index.js</em></p><pre>// Rest of the implementation<br><br>app.get(&#39;/partial-home&#39;, (req, res) =&gt; {<br>  res.contentType(&#39;text/vnd.turbo-stream.html&#39;);<br>  res.render(&#39;partials/_home&#39;);<br>});<br><br>app.get(&#39;/partial-greet&#39;, (req, res) =&gt; {<br>  const name = req.query.name ? req.query.name : null;<br>  const message = name ? `Hello ${name}!` : `Hello!`;<br><br>  res.setHeader(&#39;Content-Type&#39;, [&#39;text/vnd.turbo-stream.html&#39;]);<br>  res.render(&#39;partials/_greet&#39;, {<br>    message<br>  });<br>});<br><br>app.get(&#39;/partial-add-name&#39;, (req, res) =&gt; {<br>  res.contentType(&#39;text/vnd.turbo-stream.html&#39;);<br>  res.render(&#39;partials/_add-name&#39;);<br>});<br><br>// Rest of the implementation</pre><p>With this step, Greeting App is completely incorporated using Hotwire.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*kHOkRxe78kBWOElp" /></figure><h4>8. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next Web project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0abf87ba2336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 2] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?]]></title>
            <link>https://medium.com/@emir_75658/part-2-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose-a61b7a50c14d?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61b7a50c14d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 14:09:13 GMT</pubDate>
            <atom:updated>2023-12-21T14:09:13.762Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Part 2] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?</h3><h4>After the analysis of HTML (server side) rendering in the [Part 1], we are focusing on purely Javascript rendering in this article. In this approach whole GUI work is delegated to Client side (browser) and server performs only data operations (API). Since whole interface is handled on the Client side and there are no multiple pages (in standard HTML rendering sense) we call these applications “Single Page Applications” (SPA). Frameworks that popularized SPA-s development are Angular, React, Vue and Ember.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*WgJTIUMvP1cX0N-U" /></figure><h4>1. Article parts</h4><p>To tackle the topic of web application interface (GUI) rendering and to compare available approaches, the article is split into following parts:</p><ul><li><a href="https://blog.gradient.ba/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">HTML and HTML partials rendering[Part 1]</a>,</li><li><strong>Javascript rendering[This part],</strong></li><li>Hotwire [Part 3],</li><li>Conceptual differences of all approaches and how to choose the most applicable one {Part 4].</li></ul><h4>2. GitHub Repository</h4><p>There are two solutions presented in this article and complete implementation of solutions shown in this article can be cloned from GitHub repositories:</p><ul><li><a href="https://github.com/emir-gradient/cursor-tracking-simple-javascript-example">GitHub - emir-gradient/cursor-tracking-simple-javascript-example: Simple javascript rendering example for cursor tracking</a></li><li><a href="https://github.com/emir-gradient/greeting-app-react">GitHub - emir-gradient/greeting-app-react: Example Greeting App incorporated in React.</a></li></ul><h4>3. Concept of Javascript Rendering</h4><p>Javascript is a scripting or programming language that can be executed in the web browser (as the part of single HTML page) and can add dynamic behavior to the web page. Looking into basic operations, it allows us to create, modify, remove and animate HTML elements as the result of some event happening (“mouse click” as user interaction is one example).</p><p>Being able to manipulate all HTML elements on the web page allows as to performin Javascript rendering. So, instead of server building interface on every user’s request, that work is delegated to the browser side. More precisely, to the Javascript side.</p><p>Relevant term, when it comes to Javascript rendering, is “Document Object Model” (DOM). DOM is the data representation of the objects that comprise the structure and content of a HTML document on the web. Javascript has access to DOM, to manipulate it, and as the result of that manipulation, presented web interface changes (browsers react to DOM manipulations by rendering applied DOM manipulations).</p><p>The following example describes Javascript usage to make interactive web page. It includes section for rendering elements to the HTML body, and to add interactivity to it. Note how HTML body in this example consists of the &lt;script&gt; tag only.</p><p>This example shows current coordinates of the cursor on the webpage. Also, it updates those coordinates in the real time whenever cursors moves.</p><p>index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Simple JS User Interaction Example&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;script src=&quot;js/simple-js-user-interaction-example.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>js/simple-js-user-interaction-example.js</p><pre>// INITIAL INTERFACE CREATION PART<br><br>// Invent new div HTML element<br>const titleDiv = document.createElement(&#39;div&#39;);<br><br>// Configure its content.<br>titleDiv.innerHTML = &#39;&lt;h1&gt;Cursor position on the page:&lt;/h1&gt;&#39;;<br><br>// Append it to the bottom of HTML body element<br>document.body.append(titleDiv);<br><br>const cursorPositionDiv = document.createElement(&#39;div&#39;);<br>cursorPositionDiv.innerText = &#39;x: 0.00, y: 0.00&#39;;<br>document.body.append(cursorPositionDiv);<br><br>// INTERACTIVE PART<br>// Function to be executed on every mouse move over the web page window.<br>window.onmousemove = function (event) {<br>    // Fill in `cursorPositionDiv` with content of the current mouse coordinates.<br>    cursorPositionDiv.innerText = `x: ${event.clientX}, y: ${event.clientY}`;<br>};</pre><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*JMbTliPD2MQMDdTN" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*CwcI3BDroNChTIcP" /></figure><h4>4. SPA Frameworks and Four Main Concerns</h4><p>Looking at previously presented relatively simple example, one can imagine how complete web application that solves relatively large set of business problems might become hardly maintainable and unstable. To point couple of reasons out:</p><ul><li>Absence of consistency: In one section <em>innerHTML</em> of element is modified, in another one it is <em>innerText</em>.</li><li>Absence of structure: There are simply two sections (marked by comments), one for <em>Initial Rendering</em>, and another one for <em>Interactivity Updates</em>.</li><li>Absence of cross-browser support: Some of the operations might not be supported in all browsers.</li><li>Absence of performance optimization: There is simple function that replaces <em>innerText</em> of <em>cursorPositionDiv</em> on every ‘<em>mousemove</em>’ event being emitted. Meaning that browser will refresh given `div` content whenever it is possible for it to do so. This rendering operation is completely independent of any other rendering operations that might be needed in larger application.</li></ul><p>Still, since previous example does single initial rendering of the content, and single interactivity operation, one can safely argue that implementation is completely fine and every additional improvement on aforementioned points is an overkill.</p><p>Now, if we look at any more complex example, we see that there is a need to first design some structured, consistent, cross-browser supported and highly performant Javascript library. When that structure is enforced at some level higher than language-level, we call that library Framework, and when that framework strives to solve these four main concerns for Javascript rendering (on multiple business complexity levels), we call it “SPA Framework”.</p><p>Popular SPA Frameworks in the moment of writing this article are Angular, React, Vue and Ember.</p><h4>5. Choice of SPA Framework for “Greeting App”</h4><p>To be able to compare different web rendering approaches (in [Part 4] of this article) intent is to develop the same “Greeting App” example application using them. Specification (and functionality scope) can be read in <a href="https://blog.gradient.ba/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose">HTML and HTML partials rendering [Part 1]</a>,</p><p>To choose between these SPA frameworks, in general, we should consider multiple factors relevant for the business case we are trying to solve. When it comes to the “Greeting App” and its scope, every of these frameworks is sufficient, so without particular reason, in this article React.js is utilized.</p><h4>6. Starting React Application Development</h4><p>To develop React web application in this article, “Create React App” is utilized. It provides us with solid starting point, to be able to work on our React application.</p><p>To create initial application, execute the following command:</p><pre>npx create-react-app greeting-app</pre><p>Result of this command is that initial React template will be downloaded and configured in “greeting-app” directory. Inside that directory is root of the project. To run your application in development environment, you need to execute configured ‘start’ script:</p><pre>npm start</pre><p>As the result, development server starts, it opens the browser and loads our React application.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*GtN-VVOvtFqXIrWG" /></figure><h4>7. Rendering using React</h4><p>Entry point for every SPA application is initial HTML file with one empty div. That div, after loading SPA framework, is filled by SPA framework rules (in this case React). Body of initial HTML that we get as result of ‘create-react-app’ looks as follows:</p><p>public/index.html</p><pre>&lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;</pre><p>As we can see, there is single <em>&lt;noscript&gt;</em> tag and single empty div having <em>“root” </em>id. <em>&lt;noscript&gt;</em> tag is HTML tag whose content is ignored by all browsers that support Javascript. In case when web browser does not support it, it actually renders content inside the <em>&lt;noscript&gt;</em> tag (effectively ignoring <em>&lt;noscript&gt;</em> tag).</p><p>Root div is the place in HTML where we expect React to render implemented user interface.</p><p>Following source files (with explanation of details relevant for this topic) are an entry point of our React application:</p><p>src/index.js</p><pre>// Imports React modules<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import reportWebVitals from &#39;./reportWebVitals&#39;;<br><br>// Imports index.css for our SPA.<br>import &#39;./index.css&#39;;<br><br>// Imports our App component<br>import App from &#39;./App&#39;;<br><br>// Creating Root React Component / Node.<br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>    // Strict Mode component provides us with React warnings in case of potential problems, such as<br>    // possible memory leaks. It performs this only when is run in Development environment.<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>);<br><br>// Measure performance in Development environment.<br>reportWebVitals();</pre><p>Looking at this file, we see instruction to fetch “root div” utilizing <em>document.getElementById()</em> method and that div is provided as input to<strong><em> </em></strong><em>ReactDOM.createRoot() </em>method. From this point, React handles rendering “under the hood”, meaning that in the rest of our source code we will not manipulate DOM directly (utilizing <em>document</em> object), but delegate actual DOM manipulations to React modules.</p><p><em>Root.render()</em> method as an input takes two components: <em>React.StrictMode </em>and <em>App</em>.<em> App </em>is provided as the child of <em>React.StrictMode</em> component.</p><p>This HTML-like syntax is actually JSX. JSX is extension of Javascript syntax that looks similar to HTML (or HTML template language). It has full power of Javascript and practically every section written in JSX is actually preprocessed and executed as plain Javascript in the background. Instruction <em>&lt;App /&gt;</em> in HTML means nothing (it is invalid HTML tag), but in this case, it means “Render App Component” to this place.</p><p>In the <em>src/App.js</em> one can see <em>App Component</em> and JSX utilization to define its content.</p><p>src/App.js</p><pre>// Importing svg React logo and App.css content<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br><br>// App component<br>function App() {<br><br>  // JSX to render on the interface<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>        &lt;p&gt;<br>          Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;<br>        &lt;a<br>          className=&quot;App-link&quot;<br>          href=&quot;https://reactjs.org&quot;<br>          target=&quot;_blank&quot;<br>          rel=&quot;noopener noreferrer&quot;<br>        &gt;<br>          Learn React<br>        &lt;/a&gt;<br>      &lt;/header&gt;<br> &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In the implementation of <em>App</em> component, we can see interface that is actually rendered (React logo with link to “Learn React”). Term “className” utilized in JSX has the meaning of “class” in regular HTML. Since “class” is keyword in Javascript, that ambiguity had to be solved by defining another term for HTML class attribute.</p><p>Style of the page is defined in <em>src/App.css.</em></p><p>src/App.css</p><pre>.App {<br>  text-align: center;<br>}<br><br>.App-logo {<br>  height: 40vmin;<br>  pointer-events: none;<br>}<br><br>@media (prefers-reduced-motion: no-preference) {<br>  .App-logo {<br>    animation: App-logo-spin infinite 20s linear;<br>  }<br>}<br><br>.App-header {<br>  background-color: #282c34;<br>  min-height: 100vh;<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>  font-size: calc(10px + 2vmin);<br>  color: white;<br>}<br><br>.App-link {<br>  color: #61dafb;<br>}<br><br>@keyframes App-logo-spin {<br>  from {<br>    transform: rotate(0deg);<br>  }<br>  to {<br>    transform: rotate(360deg);<br>  }<br>}</pre><p>Rendering part of our application is covered through React components. Hierarchy of them is defined utilizing JSX, while actual rendering to the DOM is done by React.</p><h4>8. Greeting App Home Page</h4><p>Now, its time to change template React app provided to us to get “Greeting App” that we created in [Part 1] of this article using Express and HTML rendering concepts. To follow the requirement that we are trying to achieve, please check [Part 1] of this article.</p><p>First steps to perform are:</p><ul><li>Remove ‘src/index.css’ file,</li><li>Remove line “import ‘./index.css’;” from <em>src/index.js </em>file,</li><li>Create <em>Home Component </em>with “Example Project Body” heading.</li><li>Render <em>Home Component </em>in <em>App Component </em>(instead of current React example).</li></ul><p>After these changes, our source code looks as follows:</p><p>src/index.js</p><pre>// Imports React modules<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import reportWebVitals from &#39;./reportWebVitals&#39;;<br><br>// Imports our App component<br>import App from &#39;./App&#39;;<br><br>// Creating Root React Component / Node.<br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>    // Strict Mode component provides us with React warnings in case of potential problems, such as<br>    // possible memory leaks.<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>);<br><br>// Measure performance in Development environment.<br>reportWebVitals();</pre><p>src/App.js</p><pre>import &#39;./App.css&#39;;<br>import {Home} from &quot;./greet/Home&quot;;<br><br>function App() {<br>  return (<br>    &lt;Home /&gt;<br>  );<br>}<br><br>export default App;</pre><p>src/App.css</p><pre>body {<br>  padding: 50px;<br>  background: linear-gradient(to bottom right, #009ea7, #009ed7) fixed;<br>}<br><br>h1 {<br>  color: yellow;<br>  text-shadow: pink 2px 1px;<br>}<br><br>a {<br>  color: white;<br>  font-weight: bold;<br>}<br><br>form {<br>  height: 50px;<br>}<br><br>label {<br>  color: yellow;<br>}<br><br>input {<br>  border-radius: 10px;<br>  height: 25px;<br>}<br><br>button {<br>  height: 30px;<br>  border-radius: 10px;<br>}<br><br>.nav-separator::before {<br>  content: &quot;|&quot;;<br>  margin-left: 5px;<br>  margin-right: 5px;<br>}</pre><p>src/greet/Home.js</p><pre>export function Home() {<br>    return (<br>      &lt;&gt; <br>    &lt;h1&gt;Example Project Body&lt;/h1&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>And the resulting home page:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*NyxAjBWlsJ7JXg8_" /></figure><h4>9. Navigation</h4><p>When we are in SPA scope, navigation between “pages” is done by SPA Framework and is done in browser. In comparison with server HTML rendering, this scenario does not involve basic HTML behavior for links and forms. As the reminder, basic HTML behavior is that on user’s click to link, http request with new URL is sent to server and then based on server’s response, interface is updated.</p><p>In React, it is preferred to use <em>react-router-dom</em> module. This module provides us with necessary implementation to incorporate routing in our React application.</p><p>So, first step is to install it as dependency to our application by executing the following command:</p><pre>npm install --save react-router-dom</pre><p>Since we expect router to choose which of our components are loaded (based on the URL), it makes sense that first rendered component in our <em>App </em>is React Router component to manage this choice. Naturally, we need to configure mapping between routes and actual components.</p><p>For this purpose, <em>Default Greet</em> component is created, and router configured to properly map individual routes to individual components (ones that we decided should act like pages).</p><p>src/greet/Greet.js</p><pre>export function Greet() {<br>    return (<br>        &lt;h1&gt;Hello!&lt;/h1&gt;<br>    );<br>}</pre><p>src/App.js</p><pre>import &#39;./App.css&#39;;<br>import {Home} from &quot;./greet/Home&quot;;<br>import {createBrowserRouter, RouterProvider} from &quot;react-router-dom&quot;;<br>import {Greet} from &quot;./greet/Greet&quot;;<br><br>const router = createBrowserRouter(<br>    [<br>      {<br>        path: &#39;/&#39;,<br>        element: &lt;Home /&gt;,<br>      },<br>      {<br>        path: &#39;/greet&#39;,<br>        element: &lt;Greet /&gt;,<br>      }<br>    ]<br>);<br><br>function App() {<br>  return (<br>      &lt;RouterProvider router={router} /&gt;<br>  );<br>}<br><br>export default App;</pre><p>After these changes, when we access <a href="http://localhost:3000/"><em>http://localhost:3000/</em></a><em> </em>and <a href="http://localhost:3000/greet"><em>http://localhost:3000/greet</em></a><em> </em>components <em>Home </em>and <em>Greet</em> are rendered.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*6bwhDMZ3RaPHl6Y0" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*lLVAcL89hWTwcXhm" /></figure><p>To render navigation bar under main area where we present greeting message, <em>NavBar</em> component is created. Inside of that component, for links, we utilize <em>Link</em> component provided by <em>React Router</em> module. When it is ready, we use that component on every of our pages.</p><p>src/greet/NavBar.js</p><pre>import {Link} from &quot;react-router-dom&quot;;<br><br>export function NavBar() {<br>    return (<br>        &lt;&gt;<br>  &lt;Link to={&#39;/&#39;}&gt;Home&lt;/Link&gt;<br>  &lt;span className=&quot;nav-separator&quot; /&gt;<br>  &lt;Link to={&#39;/greet&#39;}&gt;Default Greet&lt;/Link&gt;<br>  &lt;span className=&quot;nav-separator&quot; /&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>src/greet/Home.js</p><pre>import {NavBar} from &quot;./NavBar&quot;;<br><br>export function Home() {<br>    return (<br>        &lt;&gt;<br>  &lt;h1&gt;Example Project Body&lt;/h1&gt;<br>  &lt;NavBar /&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>src/greet/Greet.js</p><pre>import {NavBar} from &quot;./NavBar&quot;;<br><br>export function Greet() {<br>    return (<br>        &lt;&gt;<br>  &lt;h1&gt;Hello!&lt;/h1&gt;<br>  &lt;NavBar /&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>These changes are resulting in rendered and functional navigation bar in the “Greet Application”.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*Feu1UzSq3HqWgvuV" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*u0R54yV7E4mjFA-6" /></figure><h4>10. Accepting the Form Input</h4><p>In Part 1, when form was submitted, request to the server was sent. Intention was that server builds new HTML to be presented in browser (with greeting message). In “Greeting App” case, we are still building the Form, and still submitting the name as the input. Difference is that given input will be processed in our application and not on the server.</p><p>To utilize this, we are improving <em>Greet </em>component to be able to accept <em>name</em> input from query parameters in URL. Additionally, we are creating <em>AddName</em> component, to define interface where our user will actually insert and submit its name.</p><p>src/greet/Greet.js</p><pre>import {NavBar} from &quot;./NavBar&quot;;<br>import {useLocation} from &quot;react-router-dom&quot;;<br><br>export function Greet() {<br><br>    const location = useLocation();<br><br>    let name = new URLSearchParams(location.search).get(&#39;name&#39;);<br>    let message = &#39;Hello!&#39;;<br>    if (name) {<br>        message = `Hello ${name}!`;<br>    }<br><br>    return (<br>        &lt;&gt;<br>  &lt;h1&gt;{message}&lt;/h1&gt;<br>  &lt;NavBar /&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>src/greet/AddName.js</p><pre>import {Form} from &quot;react-router-dom&quot;;<br><br>export function AddName() {<br>    return (<br>        &lt;&gt;<br>  &lt;h1&gt;Add your name:&lt;/h1&gt;<br>  &lt;Form method=&quot;get&quot; action=&quot;/greet&quot;&gt;<br>    &lt;label htmlFor=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>    &lt;input id=&quot;name&quot; type=&quot;text&quot; name=&quot;name&quot; /&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>  &lt;/Form&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>Having <em>AddName</em> and <em>Greet </em>components ready to process user’s input, only needed adaptations are in <em>NavBar component </em>and <em>router configuration </em>(defined in <em>App.js</em>).</p><p>src/App.js</p><pre>import &#39;./App.css&#39;;<br>import {Home} from &quot;./greet/Home&quot;;<br>import {createBrowserRouter, RouterProvider} from &quot;react-router-dom&quot;;<br>import {Greet} from &quot;./greet/Greet&quot;;<br>import {AddName} from &quot;./greet/AddName&quot;;<br><br>const router = createBrowserRouter(<br>    [<br>        {<br>            path: &#39;/&#39;,<br>            element: &lt;Home/&gt;,<br>        },<br>        {<br>            path: &#39;/greet&#39;,<br>            element: &lt;Greet/&gt;,<br>        },<br>        {<br>            path: &#39;/add-name&#39;,<br>            element: &lt;AddName/&gt;<br>        }<br>    ]<br>);<br><br>function App() {<br>  return (<br>      &lt;RouterProvider router={router}/&gt;<br>  );<br>}<br><br>export default App;</pre><p>src/greet/NavBar.js</p><pre>import {Link} from &quot;react-router-dom&quot;;<br><br>export function NavBar() {<br>    return (<br>        &lt;&gt;<br>  &lt;Link to={&#39;/&#39;}&gt;Home&lt;/Link&gt;&lt;span className=&quot;nav-separator&quot; /&gt;<br>  &lt;Link to={&#39;/greet&#39;}&gt;Default Greet&lt;/Link&gt;&lt;span className=&quot;nav-separator&quot; /&gt;<br>  &lt;Link to={&#39;/add-name&#39;}&gt;Add Name&lt;/Link&gt;&lt;span className=&quot;nav-separator&quot; /&gt;<br>&lt;/&gt;<br>    );<br>}</pre><p>With this step, Greeting App is completely incorporated in React.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*bozvpaNkNY2Y2P8o" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*Ta864-Q0ecRKqaOK" /></figure><h4>11. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next Web project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61b7a50c14d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 1] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?]]></title>
            <link>https://medium.com/@emir_75658/part-1-hotwire-between-the-html-server-side-and-the-javascript-rendering-what-to-choose-23500cd73665?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/23500cd73665</guid>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[rendering-html]]></category>
            <category><![CDATA[turbo-stream]]></category>
            <category><![CDATA[turbo-frame]]></category>
            <category><![CDATA[turbo]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 17:35:48 GMT</pubDate>
            <atom:updated>2023-12-05T17:35:48.443Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Part 1] Hotwire — between the HTML (server side) and the Javascript rendering. What to choose?</h3><h4>The user interfaces in web applications have been implemented using different methodologies over time. First, we have had classic HTML rendering. After that, we started to utilize Javascript and partial HTML views. The latest point was the utilization of javascript frameworks for complete interface renderings like React, Angular, Vue, and Ember. Hotwire turbo fits somewhere in between HTML and Javascript rendering. It turns out that there are business problem categories where each of the three approaches is preferable over the others. This article’s focus is to describe these different approaches and tackle decision-making process based on the given business problem.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*k4r2_6vOEYDaaqMR" /></figure><h4>1. Article parts</h4><p>To tackle the topic of web application interface (GUI) rendering and to compare available approaches, the article is split into following parts:</p><ul><li><strong>HTML and HTML partials rendering [This part],</strong></li><li>Javascript rendering [Part 2],</li><li>Hotwire [Part 3],</li><li>Conceptual differences of all approaches and how to choose the most applicable one {Part 4].</li></ul><h4>2. GitHub Repository</h4><p>Complete implementation of the solution shown in this article can be cloned from GitHub repository: <a href="https://github.com/emir-gradient/express-ejs-rendering">https://github.com/emir-gradient/express-ejs-rendering</a>.</p><h4>3. It all started with “HTML rendering”</h4><p>Let’s start by defining starting point in history for this article. So, the first point we analyze this from is the point in time when browsers supported HTML, CSS, and ES5 Javascript. At that moment in time, React, Angular, Vue, Ember, Backbone, etc. are not invented yet. Frameworks to support web application development by HTML rendering exist. There are Express.js, Laravel, Yii, CodeIgniter, Ruby on Rails, Django, Java Server Pages, Java Server Faces, Asp, etc.</p><p>The approach is to react to the user’s interaction using the server to provide every next page (view) in the HTML format. We can state that by this approach server builds the resulting HTML.</p><p>In the more detail, the approach is as follows:</p><ul><li>The user interacts with the server using the browser either by typing the initial page URL or clicking a link/button on the previously rendered interface.</li><li>The browser creates and sends HTTP requests to the server.</li><li>The server processes HTTP request and returns response in the HTML format back to the browser.</li><li>The browser renders the received HTML on the page.</li><li>The browser requests and receives all necessary CSS and Javascript files (based on the content in HTML).</li><li>The browser executes received CSS and Javascript files (meaning that complete user interface is shown).</li></ul><p>Following is the example project that is developed and suitable for HTML rendering.</p><p>Perhaps one of the simpler ways to present any web application server concept is to utilize Express.js from the listed frameworks. The rest of the listed frameworks follow the same principle for HTML rendering, but on a higher scale. These are providing us with additional utility functionalities that are commonly needed when building web applications (and very often are actually based on Express).</p><p>Express.js provides us with solid ground to build complete web applications with all the listed additional functionalities. In comparison with the rest of the listed frameworks, Express.js is unopinionated about how web application implementation should be built and structured, so we as developers need to include necessary additional functionalities, either by developing them or utilizing other third-party libraries to support our goal. Building production-ready web application examples in Express.js is out of the scope of this article.</p><p>To cover concepts, it is good to have a verbose framework, and not one that performs common concepts “behind the curtain”, hence Express.js with a minimum of additional libraries is utilized.</p><h4>3.1. Basic web server</h4><p>A basic web server implementation in Express.js that responds to a user’s request on <a href="http://localhost:3000/"><em>http://localhost:3000</em></a> is implemented as follows:</p><p>src/index.js</p><pre>const express = require(&#39;express&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(<br>`&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en-US&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Example Project&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Example Project Body&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>`<br>);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Example app listening on port ${port}`);<br>});</pre><p>On every user’s request for the ‘/’ path, static HTML is returned and rendered in the browser. This is not a very interesting application and can not (for now) be named an application. The correct name is a static site.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*gxDEj9XRoW_-mKvx" /></figure><h4>3.2. Dynamic greeting application</h4><p>To make one dynamic page, we decide on inputs and use <em>the req</em> parameter (Request) in our handler functions (req is the object that contains data mapped from the user’s HTTP request).</p><p>The following code section greets the user based on its name sent as a query parameter:</p><p>src/index.js</p><pre>...<br><br>app.get(&#39;/greet&#39;, (req, res) =&gt; {<br>  const name = req.query.name ? req.query.name : null;<br>  const message = name ? `Hello ${name}!` : `Hello!`;<br><br>  res.send(<br>`&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en-US&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Example Project&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;${message}&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>`<br>);<br>});<br><br>...</pre><p>The /greet page is not static. Its content depends on the input provided in the HTTP request. In this example, one can recognize that the processing of input data and rendering are separated. The greeting message is changed depending on the existence and content of the query parameter <em>name</em> in the request. When the final <em>message</em> is ready then it is used in the rendering phase.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*UXkbyy55VUycVNoe" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*XPnkNEZdD6o6I4t6" /></figure><h4>3.3. Separate rendering from processing</h4><p>To separate our processing from rendering in the server implementation, we usually include a template engine. In this article, we are utilizing ejs (Embedded Javascript) as a template engine. It allows us to organize our configurable HTML sections (templates) into different files, parameterize them, and write javascript inside the templates when we need dynamic behavior. After restructuring and utilization of ejs, the content of our files is:</p><p>src/index.js</p><pre>const express = require(&#39;express&#39;);<br><br>const app = express();<br>const port = 3000;<br><br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  // Rendering<br>  res.render(&#39;home&#39;);<br>});<br><br>app.get(&#39;/greet&#39;, (req, res) =&gt; {<br>  // Processing<br>  const name = req.query.name ? req.query.name : null;<br>  const message = name ? `Hello ${name}!` : `Hello!`;<br><br>  // Rendering<br>  res.render(&#39;greet&#39;, {<br>    message<br>  });<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Example app listening on port ${port}`);<br>});</pre><p>With ejs included, HTML is moved into <em>home.ejs</em> and <em>greet.ejs</em> view files. Common sections of these two pages are moved to <em>partials/header.ejs</em> and <em>partials/footer.ejs</em> files. The resulting content is as follows:</p><p>views/home.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;h1&gt;Example Project Body&lt;/h1&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>views/greet.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Greeting Example&#39; }); %&gt;<br><br>&lt;h1&gt;&lt;%= message %&gt;&lt;/h1&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>views/partials/header.ejs</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en-US&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><p>views/partials/footer.ejs</p><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>When rendering is performed, a single HTML response is returned from the server and rendered in the browser.</p><p>This means that Express takes care of processing HTTP request/response and ejs takes care of filling in provided arguments (like <em>message </em>and <em>title</em>), combining views and partials (processing <em>include </em>instruction).</p><h4>3.4. Accept the user’s input</h4><p>To take the user’s input, server renders the HTML form that the user should fill out and then make an HTTP request with filled data. To achieve that, in <em>index.js </em>we define a handler that is supposed to render input form as follows:</p><p>src/index.js</p><pre>...<br><br>app.get(&#39;/add-name&#39;, (req, res) =&gt; {<br>  res.render(&#39;add-name&#39;);<br>});<br><br>...</pre><p>and proper view:</p><p>src/add-name.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;h1&gt;Add your name:&lt;/h1&gt;<br>&lt;form method=&quot;get&quot; action=&quot;/greet&quot;&gt;<br>    &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>    &lt;input id=&quot;name&quot; type=&quot;text&quot; name=&quot;name&quot;&gt;<br><br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>With this implementation, when the user accesses /add-name route, it is presented with the HTML form to fill in its name. By clicking <em>Submit</em> button, GET HTTP request to /greet route is sent with <em>name </em>in query parameters.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*rQibd0CVrMND8PSN" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*b83T6dYvGsGuktbO" /></figure><h4>3.5. Navigation</h4><p>To allow users to navigate between pages without using the browser address bar to actually type URLs, we can build a simple Navigation Bar as follows:</p><p>partials/navbar.ejs</p><pre>&lt;% for (const navItem of navItems) { %&gt;<br>    &lt;a href=&quot;&lt;%= navItem.path %&gt;&quot;&gt;&lt;%= navItem.title %&gt;&lt;/a&gt; |<br>&lt;% } %&gt;</pre><p>To make sure the navbar is visible on the bottom of every page, we can include it in the footer right before the closing &lt;/body&gt; tag.</p><p>partials/footer.ejs</p><pre>&lt;%- include(&#39;navbar&#39;, { navItems: [<br>    {<br>       path: &#39;/&#39;,<br>       title: &#39;Home&#39;<br>    },<br>    {<br>       path: &#39;/greet&#39;,<br>       title: &#39;Default Greet&#39;<br>    },<br>    {<br>       path: &#39;/add-name&#39;,<br>       title: &#39;Add Name&#39;<br>    }<br>] }); %&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After these changes, users can navigate between available pages in the web application.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*BWqh7UGxTwhJr0U_" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*sv3oQme9YiZ5NQ6l" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*51bs39KFHL1cUoU1" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*fhWYlbqDd6wAUXBU" /></figure><h4>3.6. CSS / Styling</h4><p>When we do HTML rendering we provide CSS as a separate asset, providing it from the same server that serves the application or an independent external server (like CDN).</p><p>To provide it from the Express server in the example application, we define a directory that is statically served as follows:</p><p>src/index.js</p><pre>...<br><br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br><br>// Add this line<br>app.use(express.static(&#39;public&#39;));<br><br>...</pre><p>After that we place our stylesheets in the public directory like in the following example:</p><p>public/example-application.css</p><pre>body {<br>    padding: 50px;<br>    background: linear-gradient(to bottom right, #009ea7, #009ed7) fixed;<br>}<br><br>h1 {<br>    color: yellow;<br>    text-shadow: pink 2px 1px;<br>}<br><br>a {<br>    color: white;<br>    font-weight: bold;<br>}<br><br>form {<br>    height: 50px;<br>}<br><br>label {<br>    color: yellow;<br>}<br><br>input {<br>    border-radius: 10px;<br>    height: 25px;<br>}<br><br>button {<br>    height: 30px;<br>    border-radius: 10px;<br>}</pre><p>and finally, we put the stylesheet link in <em>header.ejs</em> partial, so it can be requested by the browser once it displays an HTML response from the server:</p><p>views/partials/header.ejs</p><pre>...<br><br>&lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;/example-application.css&quot;&gt;<br><br>...</pre><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*rNRaHUzvON9oN6FU" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*-p-jQYfbCwHdbCI7" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*UF3k9NseV6fEm3wQ" /></figure><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*ryEqOnhw0DxX5Egp" /></figure><h4>4. HTML Partials Rendering</h4><p>After HTML rendering, the next used approach is HTML partials rendering. By this design, the goal is to achieve that the server processes only part of the page that is affected by the user’s interaction. So, instead of responding to every request with full-page content, the server responds only with relevant HTML Partial.</p><p>This functionality is achieved using Javascript.</p><p>To cover the idea behind this approach we proceed with the existing web application example. When we use our example application, we can recognize that our footer links list never changes. It stays fixed during the complete application usage. So, with this approach, we will make sure to have Javascript that would perform HTTP requests for us (instead of using native HTML behavior with links and forms) and place response in the “Main Area” of the HTML page.</p><p>Additionally, our server will be capable of returning just parts of HTML related to the requested operation (HTML partials).</p><p>So, staring with index.js by defining a request to ‘/partial-home’ that will return only the home page section (without header and footer):</p><p>src/index.js</p><pre>...<br><br>app.get(&#39;/partial-home&#39;, (req, res) =&gt; {<br>  res.render(&#39;partials/_home&#39;);<br>});<br><br>...</pre><p>Following it with view changes by creating views/partials/_home.ejs and reusing it in views/home.ejs (one dedicated for a full page response).</p><p>views/partials/_home.ejs</p><pre>&lt;h1&gt;Example Project Body&lt;/h1&gt;</pre><p>views/home.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_home&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>Note that we have added div with id ‘main-area’ around the _home partial. This id is relevant for javascript implementation to define the place where server partial HTML responses need to be put.</p><p>After these changes, if we access the <a href="http://localhost:3000/partial-home">http://localhost:3000/partial-home</a> endpoint, we get the response that only contains “Example Project Body” content.</p><p>No styles, and no navigation, since only partial is rendered.</p><p>The goal is to have javascript that will fill in the div with the id “main-area” with partial results whenever the navigation item is clicked.</p><p>To achieve this, first, we prepare all partial endpoints and then we change views/partials/footer.ejs file content to target the “partial” endpoints. That implementation looks as follows:</p><p>src/index.js</p><pre>...<br><br>app.get(&#39;/partial-home&#39;, (req, res) =&gt; {<br>  res.render(&#39;partials/_home&#39;);<br>});<br><br>app.get(&#39;/partial-greet&#39;, (req, res) =&gt; {<br>  const name = req.query.name ? req.query.name : null;<br>  const message = name ? `Hello ${name}!` : `Hello!`;<br><br>  res.render(&#39;partials/_greet&#39;, {<br>    message<br>  });<br>});<br><br>app.get(&#39;/partial-add-name&#39;, (req, res) =&gt; {<br>  res.render(&#39;partials/_add-name&#39;);<br>});<br><br>...</pre><p>views/partials/_greet.ejs</p><pre>&lt;h1&gt;&lt;%= message %&gt;&lt;/h1&gt;</pre><p>views/partials/_add-name.ejs</p><pre>&lt;h1&gt;Add your name:&lt;/h1&gt;<br>&lt;form method=&quot;get&quot; action=&quot;/partial-greet&quot;&gt;<br>    &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>    &lt;input id=&quot;name&quot; type=&quot;text&quot; name=&quot;name&quot;&gt;<br><br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p>views/greet.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Greeting Example&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_greet&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>views/add-name.ejs</p><pre>&lt;%- include(&#39;partials/header&#39;, { title: &#39;Example Project&#39; }); %&gt;<br><br>&lt;div id=&quot;main-area&quot;&gt;<br>    &lt;%- include(&#39;partials/_home&#39;); %&gt;<br>&lt;/div&gt;<br><br>&lt;%- include(&#39;partials/footer&#39;); %&gt;</pre><p>views/partials/footer.ejs</p><pre>&lt;%- include(&#39;navbar&#39;, { navItems: [<br>    {<br>       path: &#39;/partial-home&#39;,<br>       title: &#39;Home&#39;<br>    },<br>    {<br>       path: &#39;/partial-greet&#39;,<br>       title: &#39;Default Greet&#39;<br>    },<br>    {<br>       path: &#39;/partial-add-name&#39;,<br>       title: &#39;Add Name&#39;<br>    }<br>] }); %&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>With these changes, it is achieved that every endpoint that returned a full HTML page still returns the full pages, so when the user arrives at any of the original URLs, it gets the whole page loaded. Links in navigation, though, now target only partial HTML rendering endpoints.</p><p>What we now want to achieve is that clicking on every one of these links and submitting every HTML form triggers a partial HTML endpoint. What we do not want is for the browser to refresh the page with new HTML as it does by default behavior.</p><p>So, the following implementation will “mimic” the browser behavior in the parts we need. We want to make a request, take the HTML response, and place it in the “main-area” div.</p><p>The following Javascript solution achieves that:</p><p>public/example-application.js</p><pre>// Execute this function when the page is loaded in the browser.<br>window.onload = function () {<br>  const navigationLinks = document.getElementsByTagName(&quot;a&quot;);<br>  const navigationLinksCount = navigationLinks.length;<br><br>  for (let i = 0; i &lt; navigationLinksCount; i++) {<br>    const navLink = navigationLinks[i];<br>    <br>    // Behavior that needs to be performed every time navigation link is clicked.<br>    navLink.onclick = function (event) {<br>      const url = event.target.attributes[&#39;href&#39;].nodeValue;<br>      makeRequestAndUpdate(url);<br><br>      event.preventDefault();<br>    }<br>  }<br><br>  overrideFormSubmit();<br>}<br><br>// Functionality that overrides default browser &quot;Form Submit&quot; behavior.<br>function overrideFormSubmit() {<br>  const forms = document.getElementsByTagName(&quot;form&quot;);<br>  const formsCount = forms.length;<br><br>  for (let i = 0; i &lt; formsCount; i++) {<br>    const formElement = forms[i];<br>    formElement.onsubmit = function (event) {<br>      const url = event.target.attributes[&#39;action&#39;].nodeValue;<br><br>      const fd = new FormData(event.target);<br>      const queryParams = new URLSearchParams(fd).toString();<br><br>      makeRequestAndUpdate(`${url}?${queryParams}`);<br><br>      event.preventDefault();<br>    };<br>  }<br>}<br><br>// Executing actual HTTP request to the server and placing the response into &#39;main-area&#39; div.<br>function makeRequestAndUpdate(url) {<br>  const xhr = new XMLHttpRequest();<br><br>  xhr.open(&quot;GET&quot;, url, true);<br><br>  xhr.onreadystatechange = function () {<br>    if (this.readyState == 4 &amp;&amp; this.status == 200) {<br>      const partialHtmlResponse = this.responseText;<br><br>      document.getElementById(&#39;main-area&#39;).innerHTML = partialHtmlResponse;<br>      overrideFormSubmit();<br>    }<br>  }<br><br>  xhr.send();<br>}</pre><p>and including it in the footer as follows:</p><p>views/partials/footer.ejs</p><pre>...<br><br>&lt;script src=&quot;/example-application.js&quot;&gt;&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>With these steps, our application renders only partials on every link click and form submit.</p><p><strong>Note</strong>: Javascript presented in this example is made for this example application and is not built for general usage.</p><p>In the following screenshot, one can see history usage utilizing ‘Netowrk tab’ where only individual requests are made and only partials retrieved.</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*Eo5G5xU9ZNcQDa-1" /></figure><h4>5. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next Web project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23500cd73665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Products between Web Shops Using Node.js]]></title>
            <link>https://medium.com/@emir_75658/migrating-products-between-web-shops-using-node-js-ee9d454b9b17?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9d454b9b17</guid>
            <category><![CDATA[woocommerce]]></category>
            <category><![CDATA[store]]></category>
            <category><![CDATA[webflow]]></category>
            <category><![CDATA[shop]]></category>
            <category><![CDATA[e-store]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 11:39:51 GMT</pubDate>
            <atom:updated>2023-11-28T11:39:51.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>Web Shop solutions that we utilize are changing over time. One becoming better than another regarding the business needs. Effective data migration between the different systems is very often needed. In this article, we describe how to perform simple migration of products from the WooCommerce store to the Webflow store.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*bqUzKBJXHiaNn4Wi" /></figure><h4>1. Migration of a Single Product from WooCommerce to Webflow</h4><p>In this article are provided steps that need to be executed to properly fetch product information from the WooCommerce store and upload it to the Webflow store. We will pick a single product by its slug and create the same one on the Webflow store where we map the product’s name, slug, description, main image, and price. Extending this functionality to migrate multiple products is relatively simple, and is briefly mentioned at the end.</p><h4>2. GitHub Repository</h4><p>Complete implementation of the solution shown in this article can be cloned from GitHub repository: <a href="https://github.com/emir-gradient/woocommerce-to-webflow-migration">https://github.com/emir-gradient/woocommerce-to-webflow-migration</a>.</p><h4>3. Preparing stores for local development</h4><p>For the WooCommerce store, one should first install WordPress and then WooCommerce plugin.</p><ul><li>Installing WordPress is described in <a href="https://wordpress.org/support/article/how-to-install-wordpress/">How to install WordPress</a>.</li><li>Installing WooCommerce is described in <a href="https://woocommerce.com/document/installing-uninstalling-woocommerce/">Installing and Uninstalling WooCommerce</a>.</li></ul><p>When it comes to Webflow since it is SaaS and not open source, for local development, we register one account on <a href="https://webflow.com/">webflow.com</a> and then follow available Webflow instructions to create an e-commerce website. While one can not publish an e-commerce site on Webflow for free, one can test it out and Webflow API can be utilized.</p><p>Once both stores are ready, we need to configure WooCommerce for API usage and get API keys. On the Webflow site, we only need to retrieve API keys.</p><ul><li>For WooCommerce, perform the steps described in the article <a href="https://woocommerce.com/document/woocommerce-rest-api/">WooCommerce REST API</a>.</li><li>For Webflow, perform the steps described in <a href="https://developers.webflow.com/">Webflow CMS API Reference</a>.</li></ul><h4>4. Starting Node.js project and installing dependencies</h4><p>Having the necessary API keys, we are ready to start developing integration code between WooCommerce and Webflow. We will utilize Node.js to implement the solution that performs product migration from WooCommerce to WebFlow.</p><p>Let us initialize an empty Node.js project:</p><pre>$ yarn init</pre><p>If you do not have or use yarn, you can utilize npm.</p><pre>$ npm install -g yarn</pre><p>Both products (WooCommerce and Webflow) have Node API clients developed and shared on the npm repository. So, we install API clients as dependencies of our project:</p><pre>$ yarn add @woocommerce/woocommerce-rest-api webflow-api</pre><p>In <strong>package.json</strong>, make sure to add <strong>the start</strong> script and define the project <strong>type</strong> as <strong>a module</strong>:</p><pre>{<br>  &quot;name&quot;: &quot;woocommerce-to-webflow-migration&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/main.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@woocommerce/woocommerce-rest-api&quot;: &quot;^1.0.1&quot;,<br>    &quot;webflow-api&quot;: &quot;^0.8.1&quot;<br>  }<br>}</pre><p>Finally, we create a directory <strong>src</strong> and create <strong>a main.js </strong>file with the following content:</p><pre>async function main() {<br>  console.log(&#39;Running&#39;);<br>}<br><br>main().then(() =&gt; {<br>  console.log(&#39;Finished&#39;);<br>});</pre><p>Run the following command in the root of the project:</p><pre>$ yarn start</pre><p>If all went properly, the result should be similar to this:</p><pre>yarn run v1.22.19<br>$ node src/main.js<br>Running<br>Finished</pre><h4>5. Fetching products from WooCommerce</h4><p>To be able to publish products to Webflow, we need to fetch them from WooCommerce store first. For this purpose, <em>WooCommerceRestApi</em> class is designed and utilized.</p><p>How to retrieve products from the WooCommerce store is presented in the following code snippet:</p><pre>const wooCommerceApiClient = new WooCommerceRestApi({<br>  url: &#39;woo-commerce store url&#39;,<br>  consumerKey: &#39;ck_abcabcabcabcabcabcbacbabcbabbcabcbabc&#39;,<br>  consumerSecret: &#39;cs_alkjlskdfjlskdfjlskdfjlskdfjlskdjflsdk&#39;,<br>  version: &#39;wc/v3&#39;<br>});<br><br>const productsResult = await this.api.get(&#39;products&#39;);</pre><p>All products from our WooCommerce store are referenced by <em>productsResult</em>.</p><p>To retrieve one product (by its slug) we will utilize the get products API endpoint with a slug filter. Also, to organize our code a bit, we will define one <em>WooCommerceIntegration</em> class. It will be utilized for all API operations related to WooCommerce API usage. The content of <em>WooCommerceIntegration</em> class is:</p><pre>import pkg from &quot;@woocommerce/woocommerce-rest-api&quot;;<br>const WooCommerceRestApi = pkg.default;<br><br>export class WooCommerceIntegration {<br>  <br>  constructor(consumerKey, consumerSecret, storeUrl) {<br>    this.consumerKey = consumerKey;<br>    this.consumerSecret = consumerSecret;<br>    this.storeUrl = storeUrl;<br><br>    this.api = new WooCommerceRestApi({<br>      url: this.storeUrl,<br>      consumerKey: this.consumerKey,<br>      consumerSecret: this.consumerSecret,<br>      version: &#39;wc/v3&#39;<br>    });<br>  }<br><br>  async getProduct(slug) {<br>    const products = await this.api.get(&#39;products&#39;, {<br>      slug<br>    });<br><br>    return products.data.length ? products.data[0] : null;<br>  }<br><br>  async getStoreCurrencyCode() {<br>    const currentCurrency = await this.api.get(&#39;data/currencies/current&#39;);<br><br>    return currentCurrency.data.code;<br>  }<br>}</pre><p>Except for instantiating <em>WooCommerceRestApi</em> and retrieving products by slug, we can also see <em>getStoreCurrencyCode</em> method in the example. We will utilize it to transfer product currency to Webflow store. An assumption is made here that all articles in source WooCommerce store have price defined in the same currency.</p><h4>6. Mapping WooCommerce product structure to Webflow</h4><p>As independent services, WooCommerce and Webflow have different data structures for representing products. To be able to provide products to Webflow API, we need to perform mapping of WooCommerce product structure to Webflow. To do so, we write mapping method as follows:</p><pre>toCreateWebflowProductDto(wooCommerceProduct, wooCommerceStoreCurrencyCode) {<br>  <br>  return {<br>    product: {<br>      fields: {<br>        _draft: true,<br>        _archived: false,<br>        name: wooCommerceProduct.name,<br>        slug: wooCommerceProduct.slug,<br>        description: wooCommerceProduct.description,<br>      }<br>    },<br>    sku: {<br>      fields: {<br>        _archived: false,<br>        _draft: true,<br>        name: wooCommerceProduct.name,<br>        slug: wooCommerceProduct.sku,<br>        &#39;main-image&#39;: {<br>          url: wooCommerceProduct.images[0].url<br>        },<br>        price: {<br>          unit: wooCommerceStoreCurrencyCode,<br>          value: wooCommerceProduct.price,<br>        }<br>      },<br>    }<br>  };<br>}</pre><p>The resulting data structure is applicable for Webflow API to create products.</p><p>Some changes/adaptations are needed though.</p><p>When we analyze further, we can recognize the two important notes why this mapper will not work properly:</p><ol><li>The description in WooCommerce is HTML5 since it includes styling of the Product description.</li><li>The price in WooCommerce is retrieved as a string. Also, it includes the decimal point. Webflow API accepts product price as the integer. So, if we want the price to be $42.00 we need to send 4200. Or, as another example, if we want the price to be $243.55, we need to send 24355 as the price value.</li></ol><p>Considering these two notes, the final <em>ProductMapper</em> implementation looks like:</p><pre>export class ProductMapper {<br>  toCreateWebflowProductDto(wooCommerceProduct, wooCommerceStoreCurrencyCode) {<br>    <br>    return {<br>      product: {<br>        fields: {<br>          _draft: true,<br>          _archived: false,<br>          name: wooCommerceProduct.name,<br>          slug: wooCommerceProduct.slug,<br>          description: this.parseDescriptionStripTags(wooCommerceProduct.description),<br>        }<br>      },<br>      sku: {<br>        fields: {<br>          _archived: false,<br>          _draft: true,<br>          name: wooCommerceProduct.name,<br>          slug: wooCommerceProduct.sku,<br>          &#39;main-image&#39;: {<br>            url: wooCommerceProduct.images[0].url<br>          },<br>          price: {<br>            unit: wooCommerceStoreCurrencyCode,<br>            value: this.parsePriceToInt(wooCommerceProduct.price),<br>          }<br>        },<br>      }<br>    };<br>  }<br><br>  parseDescriptionStripTags(description) {<br>    return description.replace(/&lt;\/?[^&gt;]+(&gt;|$)/g, &quot;&quot;);<br>  }<br><br>  parsePriceToInt(price) {<br>    if (price.indexOf(&#39;.&#39;) === -1) {<br>      return parseInt(price) * 100;<br>    } else {<br>      const parts = price.split(&#39;.&#39;);<br>      if (parts[1].length &gt; 2) {<br>        parts[1] = parts[1].substring(0, 2);<br>      } else if (parts[1].length === 1) {<br>        parts[1] += &#39;0&#39;;<br>      }<br><br>      price = parts.join(&#39;&#39;);<br><br>      return parseInt(price);<br>    }<br>  }<br>}</pre><p>By finalizing this step, we are able to retrieve the product from WooCommerce and map it to the appropriate structure for WebFlow API.</p><h4>7. Creating products in the Webflow store</h4><p>The next step in our integration is to actually upload product data to Webflow. For this purpose, we utilize <em>WebflowApi</em> class. To upload the product we need to identify our site id first. After that, we execute the following method:</p><pre>async createProduct(siteId, createWebflowProductDto) {<br>   try {<br>       await this.api.post(`/sites/${siteId}/products`, createWebflowProductDto);<br>   } catch (e) {<br>       console.log(e);<br>   }<br>}</pre><p>Complete implementation of the WebflowIntegration class, which utilizes all Webflow API operations is given in the following section:</p><pre>import Webflow from &quot;webflow-api&quot;;<br><br>export class WebflowIntegration {<br>    apiKey = null;<br>    api = null;<br><br>    constructor(apiKey) {<br>        this.apiKey = apiKey;<br>        this.api = new Webflow({ token: this.apiKey });<br>    }<br><br>    async getFirstSite() {<br>        const sites = await this.api.sites();<br><br>        return sites.length ? sites[0] : null;<br>    }<br><br>    async createProduct(siteId, createWebflowProductDto) {<br>       try {<br>           await this.api.post(`/sites/${siteId}/products`, createWebflowProductDto);<br>       } catch (e) {<br>           console.log(e);<br>       }<br>    }<br>}</pre><p>In this example, it is assumed that the user of API has only one site on Webflow. With that assumption, it is safe to take the first site (on index 0) since it should be the only one retrieved from the API.</p><h4>8. Usage of all created modules</h4><p>With all modules ready, all necessary steps for product migration from WooCommerce to Webflow are covered. The following is implemented:</p><ol><li>Retrieving product from WooCommerce,</li><li>Mapping products from WooCommerce to Webflow structure,</li><li>Publishing the product to Webflow.</li></ol><p>Finally, in<strong><em> </em></strong><em>the main.js</em> we are utilizing all created modules having the following result:</p><pre>import { WebflowIntegration } from &quot;./integrations/WebflowIntegration.js&quot;;<br>import { WooCommerceIntegration } from &quot;./integrations/WooCommerceIntegration.js&quot;;<br>import { ApiKeys } from &quot;./constants/api-keys.js&quot;;<br>import { ProductMapper } from &quot;./mapper/product-mapper.js&quot;;<br><br><br>async function load() {<br>  const productSlug = &#39;shoes&#39;;<br><br>  const webflowIntegration = new WebflowIntegration(ApiKeys.Webflow);<br>  const wooCommerceIntegration = new WooCommerceIntegration(<br>    ApiKeys.WooCommerceConsumerKey,<br>    ApiKeys.WooCommerceConsumerSecret,<br>    &quot;http://host:port&quot;);<br>  const productMapper = new ProductMapper();<br><br>  const webflowSite = await webflowIntegration.getFirstSite();<br><br>  const wooCommerceProduct = await wooCommerceIntegration.getProduct(productSlug);<br>  const wooCommerceStoreCurrencyCode = await wooCommerceIntegration.getStoreCurrencyCode();<br><br>  const createWebflowProductDto = productMapper.toCreateWebflowProductDto(wooCommerceProduct, wooCommerceStoreCurrencyCode);<br><br>  await webflowIntegration.createProduct(webflowSite._id, createWebflowProductDto);<br>}<br><br>load().then(() =&gt; {<br>  console.log(&quot;Finished!&quot;);<br>});</pre><p>By starting this program with the following command, the product with slug ‘shoes’ should be properly published to the Webflow store.</p><pre>$ yarn start</pre><h4>9. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next WooCommerce or WebFlow project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9d454b9b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Different Logos on a Single WP Instance]]></title>
            <link>https://medium.com/@emir_75658/two-different-logos-on-a-single-wp-instance-1a16068bf35b?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a16068bf35b</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[store]]></category>
            <category><![CDATA[woocommerce]]></category>
            <category><![CDATA[multiple-logos]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 13:55:44 GMT</pubDate>
            <atom:updated>2023-11-22T13:56:17.838Z</atom:updated>
            <content:encoded><![CDATA[<h4>The practice of providing the same products under multiple selling brands, combined with the popularity of WordPress and WooCommerce platforms, inspired us to tackle the given problem from a technical perspective. The focus is on the implementation of dynamic logo displaying, based on the store brand. In the scenario where the single WordPress/WooCommerce system should provide e-store functionality for different brands, there is a wide range of criteria based on which logo should be changed. It comes handy to have full control over the implementation and to be able to easily and flexibly apply necessary criteria, whenever it changes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*J_Pt0_7Pa--FKlw0" /></figure><h4>1. Chosen Logo Changing Criteria</h4><p>There are multiple criteria rules that could be defined and properly applied to decide which logo should be presented to the user. Some examples might include the device being used, the country from which the user is accessing the web store, existing cookies that might indicate a previous user’s engagement with the specific brand, etc. These examples are from the perspective that the user is a guest user. If the user is signed up and logged in to the store, the options range is wider because the system might contain information about previous purchases, preferred products, etc.</p><p>This article describes how to implement dynamic logo functionality based on the domain name. Two domain names and corresponding Logo URLs are provided through the WP Admin area. The idea is that when the user accesses the web store using “domain1.com” and “domain2.com” it is presented with “Logo 1” and “Logo 2” respectively.</p><h4>2. GitHub Repository</h4><p>Complete implementation of the solution shown in this article can be cloned from GitHub repository: <a href="https://github.com/emir-gradient/gradient-logo-changer">https://github.com/emir-gradient/gradient-logo-changer</a>.</p><h4>3. Preparing Local Environment</h4><p>First, perform the following steps:</p><ul><li>Run WordPress on a local environment by following the official WordPress documentation: <a href="https://wordpress.org/support/article/how-to-install-wordpress/">How To Install WordPress</a>.</li><li>Install the WooCommerce plugin by following the official WooCommerce documentation: <a href="https://woocommerce.com/document/installing-uninstalling-woocommerce/">Installing and Uninstalling WooCommerce</a>.</li></ul><p>After these two steps, you should have Web Store up and running.</p><p>To test the implemented solution, we utilized the <em>/etc/hosts</em> file configuration on Linux operating system. On Windows, that file is <em>C:\Windows\System32\drivers\etc\hosts</em>. On Mac-OS that file is <em>/private/etc/hosts</em>.</p><p>To achieve this, make sure to add the following lines in the <em>hosts</em> file below “127.0.0.1 localhost” line:</p><pre>127.0.0.1   domain1.com<br>127.0.0.1   domain2.com</pre><p>These lines basically inform the underlying operating system that, when requested to access domains from this list (domain1.com or domain2.com), it should resolve them to IP 127.0.0.1 instead of utilizing DNS service for domain IP resolution. This allows local testing with different domains for scenarios where access domains matter.</p><h4>4. Writing the WordPress Plugin</h4><p>To create a plugin that would be recognized by the WordPress system, we need to put the necessary plugin implementation in the<strong> </strong><em>wp-content/plugins</em><strong> </strong>directory (found in the root of the WordPress project). We created a directory <em>gradient-logo-changer </em>and an empty PHP file named <em>gradient-logo-changer.php </em>inside of it.</p><p>The first step in writing a plugin is to write a plugin header to <em>gradient-logo-changer.php</em> in the form of a PHP comment. These are parsed by WordPress for plugin recognition. So, after this action, the gradient-logo-changer.php<strong> </strong>file looks like this:</p><pre>/**<br> * Plugin Name: Gradient Logo Changer<br> * Author: Gradient Team<br> * Author URI: https://gradient.ba<br> */</pre><p>Also, as presented in the following screenshot, the WordPress system recognizes that the <em>Gradient Logo Changer</em> plugin exists:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*VB9UzsehhASgVl_m" /></figure><p>To add more details about the written plugin, check out the official WordPress documentation: <a href="https://developer.wordpress.org/plugins/plugin-basics/header-requirements/">Plugin Header Requirements</a>.</p><h4>4.1. Modifying Logo Image by Filter</h4><p>WordPress provides hooks for plugins that allow modification of final solution behavior by themes and plugins. Hooks are separated into two categories: <em>actions</em> and <em>filters</em>. For the purpose of dynamic modification of the logo image, we have utilized the<strong> </strong><em>wp_get_attachment_image_src</em> filter. WordPress invokes this filter whenever any attachment image is requested (including logo image).</p><p>Inside our plugin implementation, we write the following statement:</p><pre>add_filter(&#39;wp_get_attachment_image_src&#39;, &#39;modify_logo_image&#39;, 10, 3);</pre><p>This means that whenever an attachment image is requested in WordPress, our <em>modify_logo_image</em> function should be invoked. Argument “10” means that the filter function has a priority of 10 when executed together with other filters that are added for the <em>wp_get_attachment_image_src</em><strong> </strong>filter<strong>. </strong>Argument “3” means that provided function accepts 3 parameters. More on this can be checked here:<strong> </strong><a href="https://developer.wordpress.org/reference/functions/add_filter/"><strong>Add Filter</strong></a><strong>.</strong></p><p>Implementation of <em>modify_logo_image</em> function is as follows:</p><pre>function modify_logo_image($imageInfo, ...$args)<br>{<br>    $customLogoId = get_theme_mod(&#39;custom_logo&#39;);<br><br>    if ($args[0] === $customLogoId) {<br>        $imageInfo[0] = &#39;https://gradient.ba/assets/img/logo.png&#39;;<br>    }<br><br>    return $imageInfo;<br>}</pre><p>Filter <em>wp_get_attachment_image_src</em> is executed for every attachment image. To recognize the call executed for the logo, we utilize <em>get_theme_mod(‘custom_logo’)</em> function call to get the logo ID. Additionally, our <em>modify_logo_image</em><strong> </strong>function is invoked with the <em>args[0]</em><strong> </strong>parameter that represents the ID of the attachment image to which the filter is applied. When <em>args[0]</em><strong> </strong>matches<em> $customLogoId</em>, we can be sure that the filter is applied on the logo and we should perform our modification.</p><p>Finally, we simply replace<strong><em> </em></strong><em>$imageInfo[0]</em> with the URL of the image we need for the logo.</p><h4>4.2. Deciding on Logo Image by the Domain Criteria</h4><p>So far, we have an implementation that will modify the logo of the website with a hard-coded Gradient logo, regardless of which logo is configured in the system. The next step is the implementation of the criteria function, to actually make a decision about the logo to be presented related to the site domain. In PHP (hence in WordPress) we can recognize domain name using PHP global <em>$_SERVER[‘SERVER_NAME’]</em>. Global <em>$_SERVER[‘SERVER_NAME’] </em>gives the value of the server name as defined in the host configuration. If we need a hostname that is targeted in the user’s request we use <em>$_SERVER[‘HTTP_HOST’]</em>.</p><p>So, we create the following function:</p><pre>function get_logo_image() {<br>    $domain = sanitize_url(https://medium.com/$_SERVER[&#39;SERVER_NAME&#39;]);<br><br>    $logo = null;<br><br>    if ($domain === &#39;domain1.com&#39;) {<br>        $logo = &#39;https://...Domain1Logo.jpg&#39;;<br>    } else if ($domain === &#39;domain2.com&#39;) {<br>        $logo = &#39;https://...Domain2Logo.png&#39;;<br>    }<br><br>    return $logo;<br>}</pre><p>What it does is that it, based on the server name, returns the appropriate logo image path. In case the server name does not match any of the requested domains, then <em>null</em> is returned.</p><p>So, in our <em>modify_logo_image</em> filter function, we utilize <em>get_logo_image</em> function to retrieve a valid logo image:</p><pre>function modify_logo_image($imageInfo, ...$args)<br>{<br>    $customLogoId = get_theme_mod(&#39;custom_logo&#39;);<br><br>    if ($args[0] === $customLogoId) {<br>        $logoImageSrc = get_logo_image();<br>        if ($logoImageSrc) {<br>            $imageInfo[0] = $logoImageSrc;<br>        }<br>    }<br><br>    return $imageInfo;<br>}</pre><p>In case when there is no result image (null is returned) then we keep the default one to be presented.</p><h4>4.3. Configuration of Domains and Logo Sources through the WP Admin</h4><p>The last step is to implement configurations through WP Admin, to eliminate the necessity to change plugin implementation whenever domains or logo images change. To achieve that, we defined two domains and two logo URLs as WordPress options.</p><p>So, to intercept default WordPress behavior, first, we register the function to be executed on the<strong> </strong><em>admin_init</em> hook. This action is executed whenever the WP Admin area is initialized.</p><pre>add_action(&#39;admin_init&#39;, &#39;set_domains_settings_inputs&#39;);</pre><p>Function <em>set_domains_settings_inputs</em><strong> </strong>implementation (together with utility functions used) is implemented as follows:</p><pre>function set_domains_settings_inputs()<br>{<br>    create_settings_field(&#39;domainA&#39;, &#39;Domain A&#39;);<br>    create_settings_field(&#39;logoA&#39;, &#39;Logo A&#39;);<br>    create_settings_field(&#39;domainB&#39;, &#39;Domain B&#39;);<br>    create_settings_field(&#39;logoB&#39;, &#39;Logo B&#39;);<br>}<br><br>function create_settings_field($fieldId, $title) {<br>    add_settings_field($fieldId, $title, function () use ($fieldId) {<br>        render_settings_input($fieldId);<br>    }, &#39;general&#39;);<br><br>    register_setting(<br>        &#39;general&#39;,<br>        $fieldId<br>    );<br>}<br><br>function render_settings_input($optionName)<br>{<br>    $value = &#39;&#39;;<br>    $option = get_option($optionName);<br>    if ($option !== false) {<br>        $value = $option;<br>    }<br><br>    echo &#39;&lt;input type=&quot;text&quot; name=&quot;&#39; . $optionName . &#39;&quot; id=&#39; . $optionName .&#39;&quot; value=&quot;&#39; . $value . &#39;&quot; /&gt;&#39;;<br>}</pre><p>So, to demystify this part:</p><p>Function <em>create_settings_field</em><strong> </strong>actually registers the option with the name <em>$fieldId</em> and defines its <em>$title</em><strong> </strong>(presented on the interface). It is defined that inputs should be presented on the <em>general</em> <em>page</em> in the WordPress site settings. Function <em>render_settings_input</em><strong> </strong>actually renders input on the interface. More details on <a href="https://developer.wordpress.org/reference/functions/add_settings_field/">Add Settings Field</a> and <a href="https://developer.wordpress.org/reference/functions/register_setting/">Register Setting</a>.</p><p>After these steps, when one navigates to settings -&gt; general page of WP Admin, it should get an interface like this:</p><figure><img alt="Blog picture" src="https://cdn-images-1.medium.com/proxy/0*wqrt647KQYq9PFip" /></figure><p>At this point, saving values for Domain A, Logo A, Domain B, and Logo B should work properly.</p><p>The final action to do is to extend <em>get_logo_image()</em> function to actually read these options. To read options from the database, we use <em>get_option()</em> function. Function <em>get_logo_image()</em><strong> </strong>after this change looks like this:</p><pre>function get_logo_image() {<br>    $domain = sanitize_url(https://medium.com/$_SERVER[&#39;SERVER_NAME&#39;]);<br><br>    $domainA = get_option(&#39;domainA&#39;);<br>    $domainB = get_option(&#39;domainB&#39;);<br><br>    $logo = null;<br>    if ($domain === $domainA) {<br>        $logoA = get_option(&#39;logoA&#39;);<br>        if ($logoA !== false) {<br>            $logo = $logoA;<br>        }<br>    } else if ($domain === $domainB) {<br>        $logoB = get_option(&#39;logoB&#39;);<br>        if ($logoB !== false) {<br>            $logo = $logoB;<br>        }<br>    }<br><br>    return $logo;<br>}</pre><p>At this point, WordPress page logo should be changed based on configuration from settings.</p><h4>4.4. Complete Plugin Implementation</h4><p>After all performed steps and implementation split into files based on concerns, the resulting plugin has three files with the following contents:</p><p>gradient-logo-changer.php</p><pre>/**<br> * Plugin Name: Gradient Logo Changer<br> * Author: Gradient Team<br> * Author URI: https://gradient.ba<br> */<br><br>$pluginDir = plugin_dir_path( __FILE__ );<br><br>require_once(&quot;$pluginDir&quot; . &#39;wp-admin-settings.php&#39;);<br>require_once(&quot;$pluginDir&quot; . &#39;wp-frontend.php&#39;);<br><br>add_action(&#39;admin_init&#39;, &#39;set_domains_settings_inputs&#39;);<br>add_filter(&#39;wp_get_attachment_image_src&#39;, &#39;modify_logo_image&#39;, 10, 3);</pre><p>wp-frontend.php</p><pre>function get_logo_image() {<br>    $domain = sanitize_url(https://medium.com/$_SERVER[&#39;SERVER_NAME&#39;]);<br><br>    $domainA = get_option(&#39;domainA&#39;);<br>    $domainB = get_option(&#39;domainB&#39;);<br><br>    $logo = null;<br>    if ($domain === $domainA) {<br>        $logoA = get_option(&#39;logoA&#39;);<br>        if ($logoA !== false) {<br>            $logo = $logoA;<br>        }<br>    } else if ($domain === $domainB) {<br>        $logoB = get_option(&#39;logoB&#39;);<br>        if ($logoB !== false) {<br>            $logo = $logoB;<br>        }<br>    }<br><br>    return $logo;<br>}<br><br>function modify_logo_image($imageInfo, ...$args)<br>{<br>    $customLogoId = get_theme_mod(&#39;custom_logo&#39;);<br><br>    if ($args[0] === $customLogoId) {<br>        $logoImageSrc = get_logo_image();<br>        if ($logoImageSrc) {<br>            $imageInfo[0] = $logoImageSrc;<br>        }<br>    }<br><br>    return $imageInfo;<br>}</pre><p>wp-admin-settings.php</p><pre>function get_logo_image() {<br>    $domain = sanitize_url(https://medium.com/$_SERVER[&#39;SERVER_NAME&#39;]);<br><br>    $domainA = get_option(&#39;domainA&#39;);<br>    $domainB = get_option(&#39;domainB&#39;);<br><br>    $logo = null;<br>    if ($domain === $domainA) {<br>        $logoA = get_option(&#39;logoA&#39;);<br>        if ($logoA !== false) {<br>            $logo = $logoA;<br>        }<br>    } else if ($domain === $domainB) {<br>        $logoB = get_option(&#39;logoB&#39;);<br>        if ($logoB !== false) {<br>            $logo = $logoB;<br>        }<br>    }<br><br>    return $logo;<br>}<br><br>function modify_logo_image($imageInfo, ...$args)<br>{<br>    $customLogoId = get_theme_mod(&#39;custom_logo&#39;);<br><br>    if ($args[0] === $customLogoId) {<br>        $logoImageSrc = get_logo_image();<br>        if ($logoImageSrc) {<br>            $imageInfo[0] = $logoImageSrc;<br>        }<br>    }<br><br>    return $imageInfo;<br>}</pre><h4>5. Get an Offer</h4><p><a href="https://gradient.ba/contact-us">Contact Us</a> or <a href="https://gradient.ba/schedule-meeting">Schedule a Meeting</a> with us to get an offer for our development &amp; consulting services regarding your current or next WordPress project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a16068bf35b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of role-based access control aspects with calculated relationship roles]]></title>
            <link>https://medium.com/@emir_75658/implementation-of-role-based-access-control-aspects-with-calculated-relationship-roles-e9f9cf5998c?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f9cf5998c</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 12:46:11 GMT</pubDate>
            <atom:updated>2022-11-10T12:46:11.389Z</atom:updated>
            <content:encoded><![CDATA[<p>Authorization / Access Control implementation is an integral part of every business application. There are multiple types/levels of authorization.</p><p>In our experience, we recognized the following ones:</p><ol><li>Simple Public and Restricted access,</li><li>Authorization per Resource type,</li><li>Authorization per specific Resource.</li></ol><p>These types can be described by the following examples:</p><ol><li>Every user that is logged in to social networks (like Facebook, and LinkedIn) can access all public profiles and their public content.</li><li>The blogging system has a role named “Editor” defined. Every user that is logged in and assigned the “Editor” role can edit and publish all posts in the blogging system. The resource type in this example is “Post”.</li><li>On e-commerce sites (like eBay), there is a user that is a product seller. It can update the product status (shipped, delivered, out of stock, etc.) ONLY on the products that it sells.</li></ol><p>Cases 1 and 2 are perfectly covered in the open-source domain (in different frameworks). Scenario 3 is more specific. There are some ideas and implementations for case 3, but there is no standard approach.</p><p>Laravel has the idea of “gates” implemented for this. In this approach, for the given resource, it is decided whether the user can or can not execute the wanted action.<br>Nest.js has the idea of “abilities” (CASL) for this. Ability factory is created and it is designed in a way that abilities are defined for specific users, related to specific resources.</p><p>And many more similar implementations, ideas, approaches…</p><p>Inspired by this problem and available solutions, we have built a small open-source utility that relies on the relationship between the user and specific resources. It seems that there is available space for one more idea :).</p><p>Idea is that developers implement RelationshipResolvers. For a given user and resource, the relationship resolver calculates in which relation the user and the resource are. Depending on the user and the resource, relationship roles are calculated.</p><p>After that, existing authorization solutions for type (2) can be utilized to match users with calculated roles.</p><p>Implementation of this idea, named “relationship-roles” is published here: <a href="https://github.com/emir-gradient/relationship-roles">https://github.com/emir-gradient/relationship-roles</a></p><p>It is a low-level, framework-agnostic Node.js implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f9cf5998c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Motivations to (not) use  “const” and “let” in JavaScript in a semantically correct way]]></title>
            <link>https://medium.com/@emir_75658/motivations-to-not-use-const-and-let-in-javascript-in-a-semantically-correct-way-47c091a323ba?source=rss-205b446a4b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c091a323ba</guid>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Emir Alicic]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 22:09:33 GMT</pubDate>
            <atom:updated>2022-09-27T09:24:33.037Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Improve javascript/typescript software development efficiency by proper usage of “const”</h3><figure><img alt="Javascript code example with adequate usage of “const” and “let”." src="https://cdn-images-1.medium.com/max/1024/1*LLsqM-IOqPyANyg_bM4Eqw.png" /><figcaption>“const” and “let” usage in JavaScript</figcaption></figure><p>Let’s start with a short definition of these two:</p><p><strong>let — </strong>Keyword that creates a block-scoped reference to a value.<strong><br>const</strong> — Keyword that creates a block-scoped <strong>read-only</strong> reference to a value.</p><h3>Example problem</h3><p>For this topic, we can check the problem and implementation described in the next gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f00acb83dccdedefa722b91645e8f81/href">https://medium.com/media/8f00acb83dccdedefa722b91645e8f81/href</a></iframe><h3>The semantically correct way of using “const” and “let”</h3><p>The semantically correct way to use <em>const</em> and <em>let</em> references is that inside the code block where we declare them, we <strong>do</strong> <strong>reassign</strong> <strong>every</strong> <em>let</em> reference, at least in one conditional scenario, while all other references in that block are <strong>const </strong>(let’s collectively <strong>banish</strong> <em>var</em><strong> </strong>from JavaScript).</p><p>One possible implementation applying described semantics is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/590769755b9afcb7bdaa84a54058244e/href">https://medium.com/media/590769755b9afcb7bdaa84a54058244e/href</a></iframe><p>If all references were <em>let</em>, the result of our code execution, in the sense of data these references reference to, would be the same.</p><p>So, this brings us to the next motivation:</p><h3>Motivation not to use “const”</h3><p>While implementing the solution, defining all references as <em>let </em>references provide a developer with the flexibility to reassign every reference value in the way its algorithm requires it.</p><p>This scenario <strong>might</strong> occur during the implementation of the algorithm, during debugging and bug-fixing, and during extending the algorithm to support some new feature (that might again lead to debugging and bug-fixing).</p><p>So, it seems pretty practical.</p><p>Upper code example, if everything was written using <em>let</em>, would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/762e85fc6d76941b9f9faef48a7a113c/href">https://medium.com/media/762e85fc6d76941b9f9faef48a7a113c/href</a></iframe><h3>Motivation to use “const”</h3><p>Let’s ignore “<em>it is semantically correct</em>” and “<em>JavaScript engine can provide better performance</em>” definitions of motivation. Former one because the “semantic correctness” definition is the consequence of motivation, not the cause. Later one because JavaScript engine <strong>might be/is/will be</strong> capable of recognizing that <em>let </em>reference is not reassigned in the block and treat it as <em>const </em>anyway. So, it might not be relevant from an engine perspective.</p><p>One of the reasons to use <em>const</em> semantically correct way is <strong>More effective cold reading </strong>from your colleagues and you in the future (when you do not remember logic around it). The additional reason involves <strong>More effective refactoring</strong>. These two are described in the next sections in more detail.</p><h4>More effective cold reading</h4><p>Cold reading is a process where the developer reads the code, tries to understand it, and anticipates the result of its execution. It is significantly easier to follow the execution flow knowing that <em>const</em> references <strong>will not </strong>change and <em>let </em>references <strong>will </strong>change.</p><p>In the next example, the reader can expect (and expects by good practices) to see the change of reference <strong>total</strong>. The rest of the references (with exception of <strong>i </strong>utilized<strong> </strong>as for-loop counter) are <em>const </em>and are utilized only to hold required processing values for the algorithm to work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df13b1beba6b48cf34603e70bc0477a3/href">https://medium.com/media/df13b1beba6b48cf34603e70bc0477a3/href</a></iframe><h4><strong>More effective refactoring</strong></h4><p>The assumption for this scenario is that inside the code block, there is the functionality that the developer wants to reuse. The first level of refactoring is to isolate given functionality to <em>function </em>and invoke it in a given place. If all references declared “before” that functionality are <em>const </em>references, the developer can safely move it without a detailed analysis of that functionality implementation.</p><p>The refactoring process is straightforward:<br>-&gt; Move that functionality to a separate function.<br>-&gt; Check which references were needed, and define them as input parameters of the function.<br>-&gt; Check which references, invented in that functionality part, are needed “after” that functionality and return them from the newly invented function.<br>-&gt; Invoke that function in a given place.</p><p>For example, if one focuses on this part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e62a2e432e79bdd31680c9788cd5e1/href">https://medium.com/media/b8e62a2e432e79bdd31680c9788cd5e1/href</a></iframe><p>By following the upper refactoring steps, we end up with the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84be335b7d006a74b23f1f80164d1570/href">https://medium.com/media/84be335b7d006a74b23f1f80164d1570/href</a></iframe><p>So, the original function snippet after refactoring is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc0761ac76b6211215710aacf04345a/href">https://medium.com/media/cfc0761ac76b6211215710aacf04345a/href</a></iframe><p>If references “before” functionality were <em>let </em>that were not reassigned in the whole block, then that state gives <strong>significant</strong> <strong>complexity</strong> to the refactoring process.</p><p>The approach would be:<br>-&gt; Extend the scope that is moved to a separate function to include these <em>let </em>references.<br>-&gt; Perform all steps from the previous scenario.<br>-&gt; <strong>Realize</strong> (or even worse — <strong>do not</strong>) that <em>let</em> is invented in a newly created function just to be returned for later usage.<br>-&gt; Move it back to starting block (original block) if <strong>realization</strong> from the previous step happened.</p><p>The alternative approach, which is safe in comparison to the last one, but much more inefficient, is:<br>-&gt; Check for every <em>let </em>reference in the block, to identify if it is reassigned in the reusable functionality (since not — refactoring is safe to proceed).<br>-&gt; Perform all steps from standard refactoring.</p><h3>Conclusion</h3><p>One developer (and/or development team) can develop efficiently in the long run under next circumstances:</p><p>1) It is effective in writing implementations for new features.</p><p>2) It is working on a code base that is in a long run significantly easier to maintain.</p><p>3) It is capable to provide a code base which is easier to maintain.</p><p><strong>Effective maintenance</strong> is an important part of software development, and that might be the <strong>main motivation</strong> to use “const” and “let” in JavaScript in a semantically correct way.</p><p>The significance of this practice becomes higher by understanding that <strong>a big part </strong>of the final solution consists of references/variables and manipulation of the same.</p><p>Please, do not hesitate to comment with your opinion on this content. Did I miss out on any other significant motivation in this chapter or did I misstate some part?</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c091a323ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>