<?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 Frederic Henri on Medium]]></title>
        <description><![CDATA[Stories by Frederic Henri on Medium]]></description>
        <link>https://medium.com/@frederic.henri?source=rss-2504ac9e1697------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*C4VYz_K5fLU4H3hX.</url>
            <title>Stories by Frederic Henri on Medium</title>
            <link>https://medium.com/@frederic.henri?source=rss-2504ac9e1697------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:56:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frederic.henri/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[Compare 4 LLM on Stock Market investment]]></title>
            <link>https://wire.insiderfinance.io/compare-4-llm-on-stock-market-investment-8b001853f2de?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b001853f2de</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 11:11:06 GMT</pubDate>
            <atom:updated>2026-02-22T08:55:05.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Compare 5 AI LLMs on Stock Market investment strategy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WZDHVki6E38Yx5lT" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we’ll review how AI can help us analyze stock market data and provide tools to make our decision. We will review following Large Language Model:</p><ul><li>Anthropic</li><li>ChatGPT</li><li>Gemini</li><li>MistralAI</li><li>(Added 12/12/2024) Perplexity AI</li></ul><p>Before we go to the results, we will see what data we’ll give and how we do calculate a series of KPI so the LLM will analyse based on this, we are not asking LLM to calculate themselves or get the sentiment from anywhere else but just based on the data we’ll provide them.</p><p>We are doing a series of KPIs (you can review the previous article on <a href="https://medium.com/@frederic.henri/top-5-kpis-indicators-for-stock-market-analysis-in-python-6be978e6c616">https://medium.com/@frederic.henri/top-5-kpis-indicators-for-stock-market-analysis-in-python-6be978e6c616</a> to understand more about those KPIs) and we will do the analysis on the magnificent seven stocks.</p><p>Here is the code below I am using to run the calculation of KPIs on a period of the last 2 years</p><pre># Install necessary libraries<br>!pip install yfinance <br><br>## Libraries<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import yfinance as yf<br><br># Function to calculate start and end dates based on the number of years from today<br>def calculate_date_range(years):<br>    end_date = datetime.today()<br>    start_date = end_date - timedelta(days=years * 365)<br>    return start_date.strftime(&#39;%Y-%m-%d&#39;), end_date.strftime(&#39;%Y-%m-%d&#39;)<br><br># Calculates and returns key performance indicators (SMA, RSI, Bollinger Bands, P/E Ratio, Beta, and MACD) for a list of stock tickers over a specified date range.<br>def calculate_kpis(tickers, start_date, end_date):<br>    &quot;&quot;&quot;<br>    Calculate KPIs for a list of stocks over a given time period.<br><br>    Parameters:<br>    tickers (list): A list of stock ticker symbols.<br>    start_date (str): The start date for the analysis.<br>    end_date (str): The end date for the analysis.<br><br>    Returns:<br>    dict: A dictionary containing the KPIs for each stock.<br>    &quot;&quot;&quot;<br>    kpi_data = {}<br>    for ticker in tickers:<br><br>        # Download historical stock data<br>        stock = yf.Ticker(ticker)<br>        data = stock.history(start=start_date, end=end_date)<br>        kpi_data[ticker] = {}<br><br>        # get Simple Moving Average 50 and 200 periods<br>        sma50 = data[&#39;Close&#39;].rolling(window=50).mean()<br>        sma200 = data[&#39;Close&#39;].rolling(window=200).mean()<br>        kpi_data[ticker][&#39;SMA50&#39;] = sma50<br>        kpi_data[ticker][&#39;SMA200&#39;] = sma200<br><br>        # Calculate RSI<br>        delta = data[&#39;Close&#39;].diff()<br>        gain = (delta.where(delta &gt; 0, 0)).rolling(window=14).mean()      # Average gains<br>        loss = (-delta.where(delta &lt; 0, 0)).rolling(window=14).mean()     # Average losses<br>        rs = gain / loss                                                  # Relative strength<br>        rsi = 100 - (100 / (1 + rs))                                      # RSI formula<br>        kpi_data[ticker][&#39;RSI&#39;] = rsi<br><br>        # Calculate Bollinger Bands<br>        middle_band = data[&#39;Close&#39;].rolling(window=20).mean()                     # Middle band (SMA)<br>        upper_band = middle_band + 2 * data[&#39;Close&#39;].rolling(window=20).std()     # Upper band<br>        lower_band = middle_band - 2 * data[&#39;Close&#39;].rolling(window=20).std()     # Lower band<br>        kpi_data[ticker][&#39;Bollinger Bands&#39;] = {<br>            &#39;Middle Band&#39;: middle_band,<br>            &#39;Upper Band&#39;: upper_band,<br>            &#39;Lower Band&#39;: lower_band<br>        }<br><br>        # Calculate P/E Ratio<br>        try:<br>            eps = stock.info.get(&#39;trailingEps&#39;) # Get trailing EPS<br>            if eps and eps != 0:<br>                pe_ratio = data[&#39;Close&#39;] / eps<br>                kpi_data[ticker][&#39;P/E Ratio&#39;] = pe_ratio # Calculate P/E ratio<br>            else:<br>                kpi_data[ticker][&#39;P/E Ratio&#39;] = None<br>        except Exception as e:<br>            kpi_data[ticker][&#39;P/E Ratio&#39;] = None<br>            print(f&quot;An error occurred with ticker {ticker} P/E Ratio: {e}&quot;)<br><br>        # Calculate Beta<br>        try:<br>            beta = stock.info.get(&#39;beta&#39;) # Get beta value<br>            kpi_data[ticker][&#39;Beta&#39;] = beta<br>        except Exception as e:<br>            kpi_data[ticker][&#39;Beta&#39;] = None<br>            print(f&quot;An error occurred with ticker {ticker} Beta: {e}&quot;)<br><br>        # Calculate MACD<br>        ema_12 = data[&#39;Close&#39;].ewm(span=12, adjust=False).mean()    # 12-day EMA<br>        ema_26 = data[&#39;Close&#39;].ewm(span=26, adjust=False).mean()    # 26-day EMA<br>        macd = ema_12 - ema_26    # MACD line<br>        signal = macd.ewm(span=9, adjust=False).mean()   # Signal line<br>        histogram = macd - signal    # MACD histogram<br>        kpi_data[ticker][&#39;MACD&#39;] = {<br>            &#39;MACD&#39;: macd,<br>            &#39;Signal Line&#39;: signal,<br>            &#39;MACD Histogram&#39;: histogram<br>        }<br><br>    return kpi_data<br><br><br># Define the number of years for the analysis<br>years = 2<br><br># Calculate the start and end dates<br>start_date, end_date = calculate_date_range(years)<br><br># List of assets to analyze<br>tickers = [&#39;AAPL&#39;, &#39;AMZN&#39;, &#39;GOOGL&#39;, &#39;META&#39;, &#39;MSFT&#39;, &#39;NVDA&#39;, &#39;TSLA&#39;]<br><br># Calculate KPIs for the defined tickers and date range<br>kpi_data = calculate_kpis(tickers, start_date, end_date)</pre><p>Here is the prompt that we will use for each model:</p><pre># Create a prompt to generate an executive summary with recommendations based on KPI data<br>prompt = f&quot;&quot;&quot; Read this data {kpi_data} and provide an executive summary with recommendations for each asset. This should be presented with 2 tables format.<br>The 1st table will recap the KPIs elements (in row the assets, and KPIs in columns with their value and how to interpret).<br>In the 2nd table you will give the following information:<br>- The current trend (uptrend, downtrend or range) for range indicate the lower and upper boundaries (zone price)<br>- The recommendation<br>- The confidence in the recommendation<br>- The elements of the recommendation<br>&quot;&quot;&quot;</pre><p>In the next section we’ll review the responses from the 4 AI Assistants. I just copy/paste the whole result and because Medium does not handle table I copy the table data in excel and screenshot.</p><p>I will run in alphabetical order so its not about personal preference.</p><h3>Anthropic</h3><p>Anthropic API Key: <a href="https://console.anthropic.com/settings/keys">https://console.anthropic.com/settings/keys</a></p><h4>Python code</h4><pre>!pip install langchain-anthropic<br><br>from langchain_anthropic import ChatAnthropic<br><br>ANTHROPIC_API_KEY=&quot;sk-xxxxxx&quot;<br><br># Function to initialize OpenAI LLM model<br>def initialize_llm_Anthropic(api_key):<br>    &quot;&quot;&quot;<br>    Initialize the ChatAnthropic language model.<br><br>    Parameters:<br>    api_key (str): The API key for accessing the OpenAI service.<br><br>    Returns:<br>    ChatAnthropic: The initialized language model.<br>    &quot;&quot;&quot;<br>    llm = ChatAnthropic(<br>        model=&#39;claude-3-opus-20240229&#39;,<br>        temperature=0,<br>        max_retries=2,<br>        api_key=api_key<br>    )<br><br>    return llm<br><br># Intialize Anthropic LLM<br>Anthropic_llm = initialize_llm_Anthropic(api_key=ANTHROPIC_API_KEY)<br><br>get_llm_response(llm = Anthropic_llm, prompt = prompt)</pre><p>If you want to run it with 2 years of data, it will cost roughly 33 cents. If you want to do with a larger dataset and a longer period, it can be good to get monthly consolidated data.</p><p>Here is the executive summary with recommendations for each asset, presented in two tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hagfL4fic5KGkKpdUfsfWA.png" /></figure><p>In summary, AMZN and META show the strongest buy signals based on their bullish MACD, neutral RSI, and price action within Bollinger Bands. GOOGL and NVDA display sell signals due to bearish MACD and overvalued P/E ratios. AAPL, MSFT, and TSLA are holds as they present mixed signals, with overbought RSI and overvalued P/E ratios counterbalanced by bullish MACD indicators. The confidence in these recommendations varies based on the strength and alignment of the various technical and fundamental factors.</p><h3>ChatGPT</h3><p>OpenAI API Key: <a href="https://platform.openai.com/api-keys">https://platform.openai.com/api-keys</a></p><h4>Python Code</h4><pre>!pip install openai==1.55.3 langchain-openai==0.2.11 <br><br>from langchain_openai import ChatOpenAI<br><br>chatgpt_api_key = &quot;sk-proj-xxxxx&quot;<br><br># Function to initialize OpenAI LLM model<br>def initialize_llm_ChatGPT(model, api_key):<br>    &quot;&quot;&quot;<br>    Initialize the ChatOpenAI language model.<br><br>    Parameters:<br>    model (str): The name of the language model to use.<br>    api_key (str): The API key for accessing the OpenAI service.<br><br>    Returns:<br>    ChatOpenAI: The initialized language model.<br>    &quot;&quot;&quot;<br>    llm = ChatOpenAI(<br>        model=model, <br>        temperature=0,<br>        max_tokens=None,<br>        timeout=None,<br>        max_retries=2,<br>        api_key=api_key<br>    )<br>    return llm<br><br># Intialize OpenAI LLM<br>chatgpt_llm = initialize_llm(&quot;gpt-4o&quot;, api_key=chatgpt_api_key)<br><br>get_llm_response(llm = chatgpt_llm, prompt = prompt)</pre><p>If you want to run it with 2 years of data, it will cost roughly 5 cents.</p><p>To provide a comprehensive executive summary with recommendations for each asset, we will present the data in two tables. The first table will recap the key performance indicators (KPIs) for each asset, and the second table will provide a detailed analysis including the current trend, recommendation, confidence level, and elements supporting the recommendation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sydwuCLswiKkPIJ6UXqs4w.png" /></figure><h4>Summary:</h4><ul><li><strong>AAPL, META, TSLA</strong>: Strong uptrend with high confidence in holding or buying due to bullish indicators and overbought RSI suggesting strong momentum.</li><li><strong>AMZN, NVDA</strong>: Uptrend with medium confidence; indicators suggest potential for growth but with some caution due to high P/E ratios.</li><li><strong>GOOGL, MSFT</strong>: Currently in a range; hold recommendation with medium confidence as they are near upper Bollinger Bands and have neutral RSI, indicating potential for breakout or pullback.</li></ul><p>These recommendations are based on the current technical indicators and market conditions. Investors should consider their risk tolerance and investment goals before making decisions.</p><h3>Gemini</h3><p>Gemini API Key: <a href="https://aistudio.google.com/app/apikey">https://aistudio.google.com/app/apikey</a></p><h4>Python Code</h4><pre>!pip install langchain-google-genai<br><br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br># you might need this if you run it from Colab<br>from google.colab import auth <br>auth.authenticate_user() <br><br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from google.colab import auth <br>auth.authenticate_user()<br><br>GEMINI_API_KEY=&quot;AIxxxx&quot;<br><br># Function to initialize Gemini LLM model<br>def initialize_ChatGPT_llm(model, api_key):<br>    &quot;&quot;&quot;<br>    Initialize the Gemini AI language model.<br><br>    Parameters:<br>    model (str): The name of the language model to use.<br>    api_key (str): The API key for accessing the OpenAI service.<br><br>    Returns:<br>    ChatGoogleGenerativeAI: The initialized language model.<br>    &quot;&quot;&quot;<br>    llm = ChatGoogleGenerativeAI(<br>        model=model, <br>        temperature=0,<br>        max_tokens=None,<br>        timeout=None,<br>        max_retries=2,<br>        api_key=api_key<br>    )<br>    return llm<br><br># Intialize Gemini LLM<br>gemini_llm = initialize_llm(&quot;gemini-pro&quot;, api_key=GEMINI_API_KEY)<br><br>get_llm_response(llm = gemini_llm, prompt = prompt)</pre><p>Gemini provides Free API Key and this can run under the free tier so feel free to test. Result is straight table, no additional text so I just copy the tables screenshot, I am not clear why all numbers are wrong in the 1st table but he’s able to assess on the second</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UX29qSbOuJvCmtVqUwe9pg.png" /></figure><h3>MistralAI</h3><p>MistralAI API Key: <a href="https://console.mistral.ai/api-keys/">https://console.mistral.ai/api-keys/</a></p><h4>Python Code</h4><pre>!pip install langchain_mistralai<br><br>from langchain_mistralai import ChatMistralAI<br><br>MISTRAL_API_KEY=&quot;xxxx&quot;<br><br># Function to initialize MistralAI LLM model<br>def initialize_llm_Mistral(model, api_key):<br>    &quot;&quot;&quot;<br>    Initialize the ChatMistralAI language model.<br><br>    Parameters:<br>    model (str): The name of the language model to use.<br>    api_key (str): The API key for accessing the OpenAI service.<br><br>    Returns:<br>    ChatMistralAI: The initialized language model.<br>    &quot;&quot;&quot;<br>    llm = ChatMistralAI(<br>        model=model,<br>        temperature=0,<br>        max_retries=2,<br>        api_key=api_key<br>    )<br><br>    return llm<br><br># Intialize MistralAI LLM<br>mistral_llm = initialize_llm_Mistral(&quot;mistral-large-latest&quot;, api_key=MISTRAL_API_KEY)<br><br>get_llm_response(llm = mistral_llm, prompt = prompt)</pre><p>Mistral also runs for free with a certain tier so I encourage you to test, the only thing I had to change for the screenshot is Mistral on the header of the 1st table gives full name for acronyms like <strong>SMA50 (50-Day Simple Moving Average) </strong>it was making the screenshot too large so I change but that the only thing.</p><h3>Executive Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJGCZHlxi0uaUNb6mO2dhw.png" /></figure><h3>Recommendations Summary</h3><ul><li><strong>AAPL</strong>: Strong buy recommendation due to consistent uptrend and bullish MACD indicators.</li><li><strong>AMZN</strong>: Strong buy recommendation due to consistent uptrend and bullish MACD indicators.</li><li><strong>GOOGL</strong>: Hold recommendation due to mixed signals from MACD and Signal Line.</li><li><strong>META</strong>: Strong buy recommendation due to consistent uptrend and bullish MACD indicators.</li><li><strong>MSFT</strong>: Strong buy recommendation due to consistent uptrend and bullish MACD indicators.</li><li><strong>NVDA</strong>: Hold recommendation due to mixed signals from MACD and Signal Line.</li><li><strong>TSLA</strong>: Hold recommendation due to overbought RSI and mixed signals from MACD and Signal Line.</li></ul><h4>Conclusion</h4><p>The analysis suggests a bullish outlook for most assets, with strong uptrends and bullish MACD indicators. However, caution is advised for GOOGL, NVDA, and TSLA due to mixed signals and potential reversals. Investors should monitor these assets closely and consider diversifying their portfolios to mitigate risk.</p><h3>PerplexityAI</h3><p>MistralAI API Key: <a href="https://www.perplexity.ai/settings/api">https://console.mistral.ai/api-keys/</a></p><h4>Python Code</h4><pre>!pip install langchain-community langchain-core<br><br>from langchain_community.chat_models import ChatPerplexity<br>from google.colab import userdata<br><br>PPLX_API_KEY=userdata.get(&#39;PERPLEXITY_API_KEY&#39;)<br># Function to initialize OpenAI LLM model<br>def initialize_llm_Perplexity(api_key):<br>    &quot;&quot;&quot;<br>    Initialize the ChatOpenAI language model.<br>    Parameters:<br>    api_key (str): The API key for accessing the OpenAI service.<br>    Returns:<br>    ChatPerplexity: The initialized language model.<br>    &quot;&quot;&quot;<br>    llm = ChatPerplexity(<br>        model=&quot;llama-3.1-sonar-small-128k-online&quot;,<br>        temperature=0.7,<br>        max_retries=2,<br>        api_key=api_key<br>    )<br>    return llm<br><br># Intialize Perplexity LLM<br>Perplexity_llm = initialize_llm_Perplexity(api_key=PPLX_API_KEY)<br><br>get_llm_response(llm = Perplexity_llm, prompt = prompt)</pre><p>The report below is quite verbose although it seems it got issue to get some of the data (missing in the 1st table — everything was checked and data was present in dataframe). It will cost 0,0087$ to run with the 2 years of data (and a verbose report, if you plan on using perplexity maybe it is worth looking to get more concise information)</p><h3>Executive Summary with Recommendations for Each Asset</h3><p>To provide an executive summary and recommendations for each asset, we will analyze the key performance indicators (KPIs) such as Simple Moving Averages (SMA), Relative Strength Index (RSI), Bollinger Bands, and MACD. The data provided includes SMA50 and SMA200 for each asset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ALS6VsMzUaxQGsilBl2I9g.png" /><figcaption>Table 1 — KPIs Elements</figcaption></figure><h4>Table 2: Trend, Recommendation, Confidence, and Elements</h4><ol><li><strong>AAPL</strong></li></ol><ul><li><strong>Trend</strong>: Uptrend</li><li><strong>Recommendation</strong>: Buy</li><li><strong>Confidence</strong>: Medium</li><li><strong>Elements of Recommendation</strong>: The increasing values of SMA50 and SMA200 indicate a stabilizing trend. The absence of recent RSI and MACD data makes it difficult to provide a precise analysis, but given the overall uptrend suggested by SMAs, a buy recommendation seems reasonable.</li></ul><ol><li><strong>AMZN</strong></li></ol><ul><li><strong>Trend</strong>: Uptrend</li><li><strong>Recommendation</strong>: Buy</li><li><strong>Confidence</strong>: Medium</li><li><strong>Elements of Recommendation</strong>: Similar to AAPL, the increasing values of SMA50 and SMA200 suggest stability. The recent RSI value indicates moderate overbought conditions, but given the overall uptrend, a buy recommendation is still reasonable.</li></ul><ol><li><strong>GOOGL</strong></li></ol><ul><li><strong>Trend</strong>: Range-bound</li><li><strong>Recommendation</strong>: Hold</li><li><strong>Confidence</strong>: Low</li><li><strong>Elements of Recommendation</strong>: The RSI values are indicating moderate overbought conditions, which could suggest a potential reversal in trend. The lack of clear direction from SMAs makes it hard to provide a strong buy or sell signal.</li></ul><ol><li><strong>META</strong></li></ol><ul><li><strong>Trend</strong>: Uptrend</li><li><strong>Recommendation</strong>: Buy</li><li><strong>Confidence</strong>: High</li><li><strong>Elements of Recommendation</strong>: The significant increase in values for both SMA50 and SMA200 indicates a strong uptrend. The recent RSI value is below 80, suggesting that it might not be overbought yet, which supports the buy recommendation.</li></ul><ol><li><strong>MSFT</strong></li></ol><ul><li><strong>Trend</strong>: Range-bound</li><li><strong>Recommendation</strong>: Hold</li><li><strong>Confidence</strong>: Medium</li><li><strong>Elements of Recommendation</strong>: The recent RSI value indicates moderate overbought conditions, which could suggest a potential reversal in trend. The lack of clear direction from SMAs makes it hard to provide a strong buy or sell signal.</li></ul><ol><li><strong>NVDA</strong></li></ol><ul><li><strong>Trend</strong>: Downtrend</li><li><strong>Recommendation</strong>: Sell</li><li><strong>Confidence</strong>: Medium</li><li><strong>Elements of Recommendation</strong>: Both SMA50 and SMA200 show decreasing values indicating a downtrend. The recent RSI value indicates oversold conditions but may not be enough to suggest an immediate reversal given the overall downtrend.</li></ul><ol><li><strong>TSLA</strong></li></ol><ul><li><strong>Trend</strong>: Uptrend</li><li><strong>Recommendation</strong>: Buy</li><li><strong>Confidence</strong>: High</li><li><strong>Elements of Recommendation</strong>: The significant increase in values for both SMA50 and SMA200 indicates a strong uptrend. The recent RSI value is below 80, suggesting that it might not be overbought yet, which supports the buy recommendation.</li></ul><h3>Key Insights and Recommendations Summarized in Tables Format:</h3><h4>Table Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLn89QWUUlxDzQZj18u6_A.png" /></figure><h3>Detailed Analysis for Each Asset</h3><ol><li><strong>AAPL</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> indicate stability.</li><li><strong>RSI</strong> is not available.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Buy due to stabilizing trend.</li></ul><ol><li><strong>AMZN</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> indicate stability.</li><li><strong>RSI</strong> is indicating moderate overbought conditions.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Buy due to overall uptrend despite overbought RSI.</li></ul><ol><li><strong>GOOGL</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> show no clear direction.</li><li><strong>RSI</strong> indicates moderate overbought conditions.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Hold due to lack of clear trend direction.</li></ul><ol><li><strong>META</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> show significant increase, indicating strong uptrend.</li><li><strong>RSI</strong> below 80, suggesting not overbought yet.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Buy due to strong uptrend.</li></ul><ol><li><strong>MSFT</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> show no clear direction.</li><li><strong>RSI</strong> indicates moderate overbought conditions.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Hold due to lack of clear trend direction.</li></ul><ol><li><strong>NVDA</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> show decreasing values, indicating downtrend.</li><li><strong>RSI</strong> indicates oversold conditions but may not be enough for immediate reversal given overall downtrend.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Sell due to downtrend.</li></ul><ol><li><strong>TSLA</strong>:</li></ol><ul><li><strong>SMA50</strong> and <strong>SMA200</strong> show significant increase, indicating strong uptrend.</li><li><strong>RSI</strong> below 80, suggesting not overbought yet.</li><li><strong>MACD</strong> is not available.</li><li><strong>Recommendation</strong>: Buy due to strong uptrend.</li></ul><p>This analysis provides a general overview based on limited data provided for each asset. A more comprehensive analysis would require additional KPIs like Bollinger Bands’ upper and lower bands along with MACD lines for better trend identification and confirmation of buy/sell signals.</p><p>Here is a final recap that I made to compare the different models, I think its interesting to see that they come to different conclusion, it really shows that in investment there’s no strict rule, the idea to have multiple model is also to see if there’s a consensus somewhere or where is divergence.</p><p>I am not running perplexity AI as I was running the LLM a week later, but it is interesting to look whats its output (see above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RH6vvfe_ltjbH7_Ymqqi8Q.png" /><figcaption>Data from December 6th 2024 Updated 12th 2024 with Perplexity</figcaption></figure><p>Anthropic looks more conservative, its also the only one to have a sell signal on a stock (NVDA)</p><p>Gemini (although its the only AI to buy Google stock :)) is pretty much misaligned vs the other agent also presenting a higher confidence. Maybe thats what you get with a free plan</p><p>I leave it there and probably come back in a month or 2 to provide an update with what is happening.</p><p>Of course, this is really not investment advice, all this is just some support to help you analyse market data, there’s much much more to analyse before you want to make investment decision.</p><p><strong><em>Disclaimer</em></strong><em>: The information provided in this article is for educational and informational purposes only and should not be considered financial advice. Trading in the stock market involves a high level of risk, and you should not invest money that you cannot afford to lose. Past performance is not indicative of future results. Before using this or any trading strategy, it is essential to conduct thorough backtesting and consider consulting with a financial advisor or professional. The author and platform assume no responsibility for any financial losses or damages incurred as a result of trading based on the information provided in this article.</em></p><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b001853f2de" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/compare-4-llm-on-stock-market-investment-8b001853f2de">Compare 4 LLM on Stock Market investment</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 KPIs Indicators for Stock Market Analysis in Python]]></title>
            <link>https://wire.insiderfinance.io/top-5-kpis-indicators-for-stock-market-analysis-in-python-6be978e6c616?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/6be978e6c616</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 14:13:52 GMT</pubDate>
            <atom:updated>2024-12-06T17:41:26.401Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will discuss 5 common KPIs indicators that you can use for analysing the stock market and the python implementation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*svE1Sz9hGRH3JnUk" /><figcaption>Photo by <a href="https://unsplash.com/@dawson2406?utm_source=medium&amp;utm_medium=referral">Stephen Dawson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The goal of the article is to provide analysis tool and see their implementation in python, there’s no miracle recipe how to apply them and if you should buy or sell stocks now.</p><p>An investor should have in its toolbox multiple tools, KPIs are such tool and its important to know how to use them.</p><h4>Common python code</h4><p>I’ve been running the code in <a href="https://colab.research.google.com/">Google colab</a>. Colab is a hosted Jupyter Notebook service that requires no setup to use and provides free access to computing resources. You just need a google account to run it.</p><p>This is some shared code that is will be required, so the librairies that we will be using, the timeframe (I keep 2 years which work fine, sometimes with yahoo finance you can have issues with longer timeframe)</p><pre># Install necessary libraries<br>!pip install yfinance PyPortfolioOpt<br><br>## Libraries<br>import pandas as pd<br>import numpy as np<br>from datetime import datetime, timedelta<br>import matplotlib.pyplot as plt<br>from scipy import stats<br><br>import yfinance as yf<br><br># Function to calculate start and end dates based on the number of years from today<br>def calculate_date_range(years):<br>    end_date = datetime.today()<br>    start_date = end_date - timedelta(days=years * 365)<br>    return start_date.strftime(&#39;%Y-%m-%d&#39;), end_date.strftime(&#39;%Y-%m-%d&#39;)<br><br># Define the number of years for the analysis<br>years = 2<br><br># Calculate the start and end dates<br>start_date, end_date = calculate_date_range(years)</pre><p>I have been running all codes below against the <em>Magnificent Seven</em> but will show the result against 1 stock so if you want to run it, you can get it from github (<a href="https://github.com/fhenri/FinanceAnalysis">https://github.com/fhenri/FinanceAnalysis</a>) and feel free to change with your own portofolio.</p><p>I will not go through each of the code in details, generally there will be 2 parts, first part is regarding the mathematical calculation of the KPI and a second method which takes care of the visualisation.</p><p>I try to put as much comment as I could in my code so it should be self explanatory but dont hesitate if you have any question.</p><h3>RSI (Relative Strength Index)</h3><p><a href="https://www.investopedia.com/terms/r/rsi.asp">Relative Strength Index (RSI) Indicator Explained With Formula</a></p><p>The relative strength index (RSI) is a momentum oscillator that is widely used in technical analysis of stocks and commodities to identify changes in momentum and price direction.</p><p>Momentum indicators are technical analysis tools used to determine the strength or weakness of a stock’s price trend. Momentum measures the rate of the rise or fall of stock prices.</p><p>RSI measures the speed and magnitude of a security’s recent price changes to detect overbought or oversold conditions in the price of that security.</p><p>The math formula to calculate the RSI is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*jtALO6A_wrlrCDRW" /></figure><h4>Key points</h4><ul><li>An asset is usually considered overbought when the RSI is above 70 and oversold when it is below 30.</li><li>In some situations, the RSI line crossing below the overbought line or above the oversold line can be seen by traders as a signal to buy or sell.</li><li>The RSI works best in trading ranges rather than trending markets.</li></ul><h4>Python code</h4><p>The formula is pretty basic, we need to get the Average Gain and Average Loss in the period, by default we’ll use a rolling window of 14 (pretty common value but you can make your own test with different values)</p><pre>def calculate_rsi(data, window=14):<br>    &quot;&quot;&quot;<br>    Calculate the Relative Strength Index (RSI) for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    window (int): The lookback window for RSI calculation.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    <br>    # Calculate daily price changes<br>    delta = data[&#39;Adj Close&#39;].diff()<br><br>    # Calculate the average gain and loss over the window<br>    gain = (delta.where(delta &gt; 0, 0)).rolling(window=window).mean()<br>    loss = (-delta.where(delta &lt; 0, 0)).rolling(window=window).mean()<br><br>    # Calculate the Relative Strength (RS)<br>    rs = gain / loss<br>    # Apply RSI formula<br>    rsi = 100 - (100 / (1 + rs))<br>    return rsi</pre><pre>upper_line = 80<br>lower_line = 20<br><br>def plot_rsi(data, ticker):<br>    &quot;&quot;&quot;<br>    Plot the Relative Strength Index (RSI) for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    ticker (str): The stock ticker symbol.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br><br>    # Create a figure and axes<br>    fig, ax1 = plt.subplots(figsize=(10, 7))<br><br>    # Plot the price on the primary y-axis (ax1)<br>    ax1.plot(data.index, data[&#39;Adj Close&#39;], label=&#39;Price&#39;, color=&#39;gray&#39;)<br>    ax1.set_ylabel(&#39;Price&#39;, color=&#39;gray&#39;)<br>    ax1.tick_params(axis=&#39;y&#39;, labelcolor=&#39;gray&#39;)<br><br>    # Create a secondary y-axis (ax2) for RSI<br>    ax2 = ax1.twinx()  # Create a twin Axes sharing the xaxis<br><br>    rsi = calculate_rsi(data)<br>    # Plot the RSI on the secondary y-axis (ax2)<br>    ax2.plot(data.index, rsi, label=&#39;RSI&#39;, color=&#39;blue&#39;)<br>    ax2.set_ylabel(&#39;RSI&#39;, color=&#39;blue&#39;)<br>    ax2.tick_params(axis=&#39;y&#39;, labelcolor=&#39;blue&#39;)<br>    ax2.axhline(upper_line, color=&#39;red&#39;, linestyle=&#39;--&#39;)<br>    ax2.axhline(lower_line, color=&#39;green&#39;, linestyle=&#39;--&#39;)<br><br>    # Add a title and display the legend<br>    plt.title(f&#39;RSI and Price of {ticker}&#39;)<br>    plt.xlabel(&#39;Date&#39;)<br>    fig.tight_layout()  # Adjust the layout to prevent overlapping elements<br>    plt.show()</pre><p>so now if we run it against Apple on the last 2 years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*yiJ3u9z0ZICoTQwuEXsdoA.png" /></figure><p>I am using upper line as 80 and lower line as 20 (vs recommended 70 and 30) this is a preference but again feel free to adjust based on your own decision.</p><p>You can see stock price is rising and we’re getting over 80 so might be overbought. Again dont take decision with 1 KPI only but add that to your list when you make pros and cons.</p><h3>Bollinger Bands</h3><p><a href="https://www.investopedia.com/terms/b/bollingerbands.asp">https://www.investopedia.com/terms/b/bollingerbands.asp</a></p><p>Bollinger Bands is a technical analysis tool developed by John Bollinger in the 1980s to help investors and traders gauge market volatility and identify when securities are poised to rise or fall (determine if they are over- or undervalued)</p><p>The bands appear on stock charts as three lines that move with the price. The center line is the stock price’s 20-day simple moving average (SMA). The upper and lower bands are set at a certain number of standard deviations, usually two, above and below the middle line.</p><p>The bands widen when a stock’s price becomes more volatile and contract when it is more stable. Many traders see stocks as overbought as their price nears the upper band and oversold as they approach the lower band, signalling an opportune time to trade</p><h4>Key points</h4><ul><li>Bollinger Bands is a technical analysis tool used to determine where prices are high and low relative to each other.</li><li>These bands are composed of three lines: a simple moving average (the middle band) and an upper and lower band.</li><li>The upper and lower bands are typically two standard deviations above or below a 20-period simple moving average (SMA).</li><li>The bands widen and narrow as the volatility of the underlying asset changes.</li><li>It is a Secondary indicator that is best used to confirm other analysis methods</li></ul><h4>Python Code</h4><p>To calculate the Bollinger bands, we need to calculate 3 data:</p><ul><li>Simple Moving Average (SMA) with 20 periods (we can have 20 as argument and make it more generic)</li><li>the upper and lower band by applying 2 * standard deviation against the SMA. Here we dont make it more generic as 2 is pretty common values.</li></ul><pre>def calculate_bollinger_bands(data, window=20):<br>    &quot;&quot;&quot;<br>    Calculate the Bollinger Bands for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    window (int): Simple Moving Average period.<br><br>    Returns:<br>    tuple: A tuple containing the middle, upper, and lower bands.<br>    &quot;&quot;&quot;<br>    # Calculate the middle band (simple moving average)<br>    middle_band = data[&#39;Adj Close&#39;].rolling(window=window).mean()<br><br>    # Calculate standard deviation<br>    std_dev = data[&#39;Adj Close&#39;].rolling(window=window).std()<br><br>    # Calculate Upper and Lower Bands<br>    upper_band = middle_band + (std_dev * 2)<br>    lower_band = middle_band - (std_dev * 2)<br><br>    return middle_band, upper_band, lower_band</pre><p>And we just plot all those values together in the same graph</p><pre>def plot_bollinger_bands(data, ticker, window=20):<br>    &quot;&quot;&quot;<br>    Plot the Bollinger Bands for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    ticker (str): The stock ticker symbol.<br>    window (int): Simple Moving Average period.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    # Get the Bollinger Bands using the calculation method<br>    middle_band, upper_band, lower_band = calculate_bollinger_bands(data, window)<br><br>    # Plot the closing price and Bollinger Bands<br>    plt.figure(figsize=(10, 5))<br>    plt.plot(data.index, data[&#39;Adj Close&#39;], label=&#39;Closing Price&#39;, color=&#39;gray&#39;)<br>    plt.plot(data.index, middle_band, label=&#39;Middle Band&#39;, color=&#39;blue&#39;)<br>    plt.plot(data.index, upper_band, label=&#39;Upper Band&#39;, color=&#39;red&#39;)<br>    plt.plot(data.index, lower_band, label=&#39;Lower Band&#39;, color=&#39;green&#39;)<br><br>    # Add title, labels, and legend<br>    plt.title(f&#39;Bollinger Bands of {ticker}&#39;)<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.legend()<br>    plt.show()</pre><p>Again we run it for Apple in the last 2 years</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Lil9VQCjcpa4bdrYMbId4w.png" /></figure><p>You can see how sharp this is and how the price remains within the bands, when touching the lower one, it goes back up. Again you can see the current price is on the upper band, and the bands are getting wider.</p><h3>Price-to-Earnings Ratio (P/E)</h3><p><a href="https://www.investopedia.com/terms/p/price-earningsratio.asp">Price-to-Earnings (P/E) Ratio: Definition, Formula, and Examples</a></p><p>The price-to-earnings ratio compares a company’s share price with its earnings per share. Analysts and investors use it to determine the relative value of a company’s shares in side-by-side comparisons.</p><h4>Key Points</h4><ul><li>The price-to-earnings (P/E) ratio is the proportion of a company’s share price to its earnings per share.</li><li>A high P/E ratio could mean that a company’s stock is overvalued or that investors expect high growth rates.</li><li>Companies with no earnings or are losing money don’t have a P/E ratio because there’s nothing to put in the denominator.</li><li>The two most used P/E ratios are forward and trailing P/E.</li><li>P/E ratios are most valuable when comparing similar companies in the same industry or for a single company over time.</li></ul><h4>Python Code</h4><p>Here it will be more simple, there’s no calculation to be made, this is a data we can retrieve directly from the yahoo finance</p><p>As it is mentioned above, we will display both forward and trailing P/E and since it is most valuable when comparing, we plot all magnificent seven P/E on same graph</p><pre>def plot_pe_ratios(ticker_data_dict, eps_type=&#39;trailing&#39;):<br>    &quot;&quot;&quot;<br>    Plot the Price-to-Earnings (P/E) ratios for multiple stocks on the same graph.<br><br>    Parameters:<br>    ticker_data_dict (dict): A dictionary with tickers as keys and their data as values.<br>                              Each data entry should be a tuple of (dataframe, eps)<br>    eps_type (str): Type of EPS to use - &#39;trailing&#39; or &#39;forward&#39;<br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    # Create the plot<br>    plt.figure(figsize=(12, 6))<br><br>    # Iterate through the tickers and their data<br>    for ticker, (data, eps_values) in ticker_data_dict.items():<br>        # Choose the appropriate EPS based on the type<br>        eps = eps_values[&#39;trailing&#39;] if eps_type == &#39;trailing&#39; else eps_values[&#39;forward&#39;]<br><br>        # Check if EPS value is valid<br>        if eps is None or eps == 0:<br>            print(f&quot;Skipping {ticker}: {eps_type} EPS is not available or zero&quot;)<br>            continue<br><br>        # Calculate the P/E ratio<br>        pe_ratio = data[&#39;Adj Close&#39;] / eps<br><br>        # Plot the P/E ratio for this ticker<br>        plt.plot(data.index, pe_ratio, label=f&#39;{ticker} PE Ratio&#39;)<br><br>    # Customize the plot<br>    title_type = &#39;Trailing&#39; if eps_type == &#39;trailing&#39; else &#39;Forward&#39;<br>    plt.title(f&#39;{title_type} PE Ratios of Selected Stocks&#39;)<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(f&#39;{title_type} PE Ratio&#39;)<br>    plt.legend()<br>    plt.grid(True, linestyle=&#39;--&#39;, alpha=0.7)<br>    plt.tight_layout()<br>    plt.show()</pre><pre># Prepare the data for plotting<br>ticker_data = {}<br>for ticker in tickers:<br>    stock = yf.Ticker(ticker)<br><br>    # Collect both trailing and forward EPS<br>    eps_values = {<br>        &#39;trailing&#39;: stock.info.get(&#39;trailingEps&#39;),<br>        &#39;forward&#39;: stock.info.get(&#39;forwardEps&#39;)<br>    }<br><br>    data_ticker = yf.download(ticker, start=start_date, end=end_date)<br><br>    # Store the data and EPS values in the dictionary<br>    ticker_data[ticker] = (data_ticker, eps_values)<br><br># Plot P/E ratios for trailing EPS<br>plot_pe_ratios(ticker_data, eps_type=&#39;trailing&#39;)<br><br># Plot P/E ratios for forward EPS<br>plot_pe_ratios(ticker_data, eps_type=&#39;forward&#39;)</pre><p>You can see the result and you can notice differences between trailing and forward P/E. You can see Tesla P/E is increasing even though it has always been much higher than the rest, investors are still willing to pay a lot for the earnings, so they expect the company to earn more in the coming quarters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTLosnOMDgafqKkW8mz1sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhJmH-IBtp7l9r172qKGkg.png" /></figure><h3>Beta comparison</h3><p><a href="https://www.investopedia.com/terms/b/beta.asp">What Beta Means for Investors</a></p><p>Beta is a measure of a stock’s volatility in relation to the overall market. By definition, the market, such as the S&amp;P 500 Index, has a beta of 1.0, and individual stocks are ranked according to how much they deviate from the market. A stock that swings more than the market over time has a beta above 1.0. If a stock moves less than the market, the stock’s beta is less than 1.0.</p><h4>Key Points</h4><ul><li>Beta is a concept that measures the expected move in a stock relative to movements in the overall market.</li><li>A beta greater than 1.0 suggests that the stock is more volatile than the broader market, and a beta less than 1.0 indicates a stock with lower volatility.</li><li>Beta is a component of the Capital Asset Pricing Model (CAPM), which calculates the cost of equity funding and can help determine the rate of return to expect relative to perceived risk.</li><li>Critics argue that beta does not give enough information about the fundamentals of a company and is of limited value when making stock selections.</li><li>Beta is probably a better indicator of short-term rather than long-term risk.</li></ul><p>The math formula to calculate the Beta is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*cMYEaQYcw6SRLXTI" /></figure><p>The default setting is 200 daily bars but 36 monthly bars is also commonly used for Beta.</p><h4>Python Code</h4><p>As we analyse US Stocks, we’ll use SP500 to calculated the regression analysis (S&amp;P 500 is considered to have a Beta of 1).</p><p>We’ll calculate beta for different settings (including 200 and 36 and probably look at 36 since Beta is mentioned to be a better indicatory on short term)</p><pre>def calculate_beta(ticker, start_date, end_date, beta_settings=[200, 36]):<br>    &quot;&quot;&quot;<br>    Calculate beta price of a given stock (compared to SP500) for a given period<br><br>    Parameters:<br>    ticker (str): The stock ticker symbol.<br>    start_date (str): The start date of the analysis.<br>    end_date (str): The end date of the analysis.<br>    beta_settings (list): A list of beta settings values to consider.<br><br>    Returns:<br>    DataFrame: A DataFrame containing the stock price and the beta values for each setting.<br>    &quot;&quot;&quot;<br>    stock_data = yf.download(ticker, start=start_date, end=end_date)<br>    # S&amp;P 500 index<br>    market_data = yf.download(&quot;^GSPC&quot;, start=start_date, end=end_date)  <br><br>    # Calculate daily returns for each<br>    stock_data[&#39;Return&#39;] = stock_data[&#39;Adj Close&#39;].pct_change()<br>    market_data[&#39;Return&#39;] = market_data[&#39;Adj Close&#39;].pct_change()<br><br>    # Ensure data alignment<br>    data = pd.DataFrame({<br>        &#39;Stock_Return&#39;: stock_data[&#39;Return&#39;],<br>        &#39;Market_Return&#39;: market_data[&#39;Return&#39;]<br>    }).dropna()<br><br>    # Calculate beta for each setting<br>    beta_values = {}<br>    for setting in beta_settings:<br>        # calculate covariance on market returns<br>        rolling_covariance = data[&#39;Stock_Return&#39;].rolling(window=setting).cov(data[&#39;Market_Return&#39;])<br>        # calculate variance<br>        rolling_variance = data[&#39;Market_Return&#39;].rolling(window=setting).var()<br>        # beta calculation<br>        beta_values[f&#39;Beta_{setting}&#39;] = rolling_covariance / rolling_variance<br><br>    # Merge beta values with stock data<br>    beta_df = pd.DataFrame(beta_values)<br>    beta_df.index = data.index<br>    combined_data = pd.concat([stock_data[&#39;Adj Close&#39;], beta_df], axis=1)<br>    return combined_data</pre><pre>def plot_beta(ticker, start_date, end_date, beta_settings=[200, 36]):<br>    &quot;&quot;&quot;<br>    Plot beta price of a given stock (compared to SP500) for a given period<br><br>    Parameters:<br>    ticker (str): The stock ticker symbol.<br>    start_date (str): The start date of the analysis.<br>    end_date (str): The end date of the analysis.<br>    beta_settings (list): A list of beta settings values to consider.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    # retrieve beta prices for the stock<br>    combined_data = calculate_beta(ticker, start_date, end_date, beta_settings)<br><br>    # Plot stock price and beta<br>    fig, ax1 = plt.subplots(figsize=(12, 6))<br><br>    ax1.set_title(f&quot;Stock Price and Beta ({ticker})&quot;, fontsize=16)<br>    ax1.plot(combined_data.index, combined_data[ticker], label=f&#39;{ticker} Price&#39;, color=&#39;gray&#39;)<br>    ax1.set_ylabel(&#39;Stock Price&#39;, color=&#39;gray&#39;)<br>    ax1.tick_params(axis=&#39;y&#39;, labelcolor=&#39;gray&#39;)<br><br>    ax2 = ax1.twinx()<br>    beta_values = combined_data.iloc[:, 1:]<br>    for beta_col in beta_values.keys():<br>        ax2.plot(combined_data.index, combined_data[beta_col], label=beta_col)<br>    ax2.axhline(1.0, color=&#39;red&#39;, linestyle=&#39;--&#39;)<br>    ax2.set_ylabel(&#39;Beta&#39;, color=&#39;blue&#39;)<br>    ax2.tick_params(axis=&#39;y&#39;, labelcolor=&#39;blue&#39;)<br><br>    fig.legend(loc=&quot;upper left&quot;, bbox_to_anchor=(0.1, 0.9), bbox_transform=ax1.transAxes)<br>    plt.show()</pre><p>And again we’ll run the Beta calculation for Apple on the last 2 years. The calculation takes the data from start date so the beta_200 needs already 200 days of data, the method does not retrieve prior data to do the math.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNmHzlHWDdVSdhWiTIFvTA.png" /></figure><h3>Moving Average Convergence Divergence (MACD)</h3><p><a href="https://www.investopedia.com/terms/m/macd.asp">https://www.investopedia.com/terms/m/macd.asp</a></p><p>Moving average convergence/divergence (MACD) is a technical indicator to help investors identify price trends, measure trend momentum, and identify entry points for buying or selling. It is a trend-following momentum indicator that shows the relationship between two exponential moving averages (EMAs) of a security’s price. It is one of the most popular technical tools.</p><h4>Key Points</h4><ul><li>Moving average convergence/divergence (MACD) is a technical indicator to help investors identify entry points for buying or selling.</li><li>The MACD line is calculated by subtracting the 26-period exponential moving average (EMA) from the 12-period EMA.</li><li>The signal line is a nine-period EMA of the MACD line.</li><li>MACD is best used with daily periods, where the traditional settings of 26/12/9 days is the default.</li></ul><h4>Python Code</h4><p>We’ll take default parameters, we calculate EMA with 12 and 26 period and do the math. We will add the histogram which is MACD — Signal, generally we can consider a positive histogram a bullish signal and a negatice histogral is bearish</p><pre>def calculate_macd(data):<br>    &quot;&quot;&quot;<br>    Calculate the Moving Average Convergence Divergence (MACD) for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    ticker (str): The stock ticker symbol.<br><br>    Returns:<br>    tuple: A tuple containing the MACD, signal line and histogram values<br>    &quot;&quot;&quot;<br>    # Calculate the 12-day and 26-day EMA<br>    ema_12 = data[&#39;Adj Close&#39;].ewm(span=12, adjust=False).mean()<br>    ema_26 = data[&#39;Adj Close&#39;].ewm(span=26, adjust=False).mean()<br><br>    # Calculate the MACD<br>    macd = ema_12 - ema_26<br><br>    # Calculate the signal line<br>    signal = macd.ewm(span=9, adjust=False).mean()<br><br>    histogram = macd - signal<br><br>    return macd, signal, histogram</pre><pre>def plot_macd(data, ticker):<br>    &quot;&quot;&quot;<br>    Plot the Moving Average Convergence Divergence (MACD) for a given stock.<br><br>    Parameters:<br>    data (DataFrame): The stock data.<br>    ticker (str): The stock ticker symbol.<br><br>    Returns:<br>    None<br>    &quot;&quot;&quot;<br>    macd, signal, histogram = calculate_macd(data)<br><br>    # Extract the relevant column for the histogram so we can display the bar chart<br>    # Ensure this matches your DataFrame column structure<br>    histogram = histogram[ticker]  <br><br>    # Create a figure and axes<br>    fig, ax1 = plt.subplots(figsize=(14, 7))<br><br>    # Plot the price on the primary y-axis (ax1)<br>    ax1.plot(data.index, data[&#39;Adj Close&#39;], label=&#39;Price&#39;, color=&#39;gray&#39;)<br>    ax1.set_ylabel(&#39;Price&#39;, color=&#39;gray&#39;)<br>    ax1.tick_params(axis=&#39;y&#39;, labelcolor=&#39;gray&#39;)<br><br>    # Create a secondary y-axis (ax2) for MACD<br>    ax2 = ax1.twinx()  # Create a twin Axes sharing the xaxis<br><br>    ax2.plot(data.index, macd, label=f&#39;{ticker} MACD&#39;)<br>    ax2.plot(data.index, signal, label=f&#39;{ticker} Signal Line&#39;)<br><br><br>    # Plot the histogram as bars<br>    colors = [&#39;green&#39; if h &gt;= 0 else &#39;red&#39; for h in histogram.values]<br>    #ax2.plot(data.index, histogram, label=f&#39;{ticker} MACD&#39;)<br>    ax2.bar(data.index, histogram.values, color=colors, alpha=0.5, width=1, label=&#39;Histogram&#39;)<br><br>    # Add a horizontal line at zero<br>    ax2.axhline(y=0, color=&#39;black&#39;, linestyle=&#39;--&#39;, linewidth=0.5)<br><br>    plt.title(f&#39;MACD and Signal Line of {ticker}&#39;)<br>    plt.xlabel(&#39;Date&#39;)<br>    plt.ylabel(&#39;MACD&#39;)<br>    plt.legend(loc=&quot;upper left&quot;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvcSfrbTRS-PeSfYw0J91A.png" /></figure><h4>A Message from InsiderFinance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*10x5_2smmKq8oIlf.png" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a></li><li>📚 Take our <a href="https://learn.insiderfinance.io/p/mastering-the-flow">FREE Masterclass</a></li><li><strong>📈 Discover </strong><a href="https://insiderfinance.io/?utm_source=wire&amp;utm_medium=message"><strong>Powerful Trading Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6be978e6c616" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/top-5-kpis-indicators-for-stock-market-analysis-in-python-6be978e6c616">Top 5 KPIs Indicators for Stock Market Analysis in Python</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate your users on 3rd party services using OAuth within your Telegram Bot]]></title>
            <link>https://medium.com/@frederic.henri/authenticate-your-users-on-3rd-party-services-using-oauth-within-your-telegram-bot-b0003764e83e?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0003764e83e</guid>
            <category><![CDATA[google-oauth]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 13:56:31 GMT</pubDate>
            <atom:updated>2024-11-28T13:56:31.975Z</atom:updated>
            <content:encoded><![CDATA[<p>how you can get an OAuth token from Google within a Telegram bot application and save the state across session on serverless application deployed on Cloudflare</p><p>Note: this is not to authenticate yourself using your Telegram Ids but to authenticate your bot clients into their Google account so they can interact with their google data within the chatbot.</p><p>I will assume you already read the article <a href="https://medium.com/@frederic.henri/conversation-telegram-bot-with-grammy-deployed-on-cloudflare-8f691515c365">https://medium.com/@frederic.henri/conversation-telegram-bot-with-grammy-deployed-on-cloudflare-8f691515c365</a>, in case you did not (yet!) you can read the part of <em>Creating the Telegram bot </em>so you have a bot setup and running</p><p>The scope of this bot is dead simple: we want to log you in using your google account. So lets create a google oauth credentials the bot will use</p><h3>Create the Google OAuth credentials</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSEIsz-vwsMznm4th2gZLg.png" /></figure><p>Make sure to set the URL of where the bot will be running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CALV8NSo0oILLJ6Bxh56vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAOzuO-sUXdDZUFznOCQDg.png" /></figure><p>Keep track of the <strong>Client ID</strong> and <strong>Client secret</strong>.</p><h3>Create the Telegram bot</h3><p>That is where you can review the same part from its cousin article, we will create 2 commands</p><pre>login - login through Google login<br>calendar - check your Google calendar</pre><p>and now if you go to the chat window of your new bot, you will see the menu button and the available command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*IpHNYfSgS6GTyigXgXitKQ.png" /></figure><p>We will start with a skeleton of Telegram Bot deployed on Cloudflare</p><p>The secrets required will be</p><pre>BOT_TOKEN=<br>GOOGLE_CLIENT_SECRET=&quot;&quot;</pre><p>You can use the npx wrangler secret put &lt;secret_name&gt; to push secret on the Cloudflare worker.</p><p>Since we need to store the oauth token between serverless session, we will setup <a href="https://developers.cloudflare.com/kv/">Cloudflare workers KV</a>.</p><pre>npx wrangler kv:namespace create &quot;OAUTH_STATES&quot;<br><br> ⛅️ wrangler 3.87.0 (update available 3.88.0)<br>-------------------------------------------------------<br><br>🌀 Creating namespace with title &quot;telegram-bot-OAUTH_STATES&quot;<br>✨ Success!<br>Add the following to your configuration file in your kv_namespaces array:<br>[[kv_namespaces]]<br>binding = &quot;OAUTH_STATES&quot;<br>id = &quot;xxxxxxx&quot;</pre><p>You can repeat the same for OAUTH_TOKEN namespace and then you can add the bindings in your wrangler.toml file. There are 2 fashions to store so pick the one your prefer.</p><pre># kv_namespaces = [<br>#   { binding = &quot;&lt;OAUTH_STATES&gt;&quot;, id = &quot;&lt;xxxxxxx&gt;&quot; },<br>#   { binding = &quot;&lt;OAUTH_TOKEN&gt;&quot;, id = &quot;&lt;xxxxxxx&gt;&quot; }<br># ]<br><br>[[kv_namespaces]]<br>binding = &quot;OAUTH_STATES&quot;<br>id = &quot;xxxxxxx&quot;<br><br>[[kv_namespaces]]<br>binding = &quot;OAUTH_TOKEN&quot;<br>id = &quot;xxxxxxx&quot;</pre><p>we also need to add variables for the oauth client information</p><pre>GOOGLE_CLIENT_ID=&quot;461878147901-xxxx.apps.googleusercontent.com&quot;<br>OAUTH_REDIRECT_URI=&quot;https://&lt;worker&gt;.&lt;domain&gt;.workers.dev/api/auth/callback/google&quot;</pre><h4>Start coding the bot</h4><p>we’ll install the dependencies</p><pre>npm install @googleapis/calendar grammy</pre><p><a href="https://grammy.dev/">grammY</a> is a telegram framework in typescript that simplifies the work when creating a telegram bot.</p><p>First we setup the environment and define the bot. Nothing special, if you read the grammY doc, thats all straightforward</p><pre>interface SessionData {<br> oauthToken?: string;<br>}<br>type MyContext = Context &amp; SessionFlavor&lt;SessionData&gt;;<br><br>export interface Env {<br> BOT_INFO: string;<br> BOT_TOKEN: string;<br> GOOGLE_CLIENT_ID: string;<br> GOOGLE_CLIENT_SECRET: string;<br> OAUTH_REDIRECT_URI: string;<br> OAUTH_STATES: KVNamespace;<br> OAUTH_TOKEN: KVNamespace;<br>}<br><br>export default {<br> async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise&lt;Response&gt; {<br>  const bot = new Bot&lt;MyContext&gt;(env.BOT_TOKEN, {<br>   botInfo: JSON.parse(env.BOT_INFO),<br>  });<br><br>  bot.command(&#39;hello&#39;, async (ctx) =&gt; {<br>   await ctx.reply(&#39;hello back&#39;);<br>  });<br><br>  bot.use(<br>   session({<br>    initial: (): SessionData =&gt; ({}),<br>   })<br>  );</pre><p>I just add a /hello command which echo the user message just to make sure everything is good.</p><p>Then we define the /login command:</p><ul><li>we need to store the chatId (which is the Id of the current chat, when google will send back the authorization token we need to be able to link with the current chat. Thats because we deploy in serverless so once we will not know which session the reply will be associated, we need to pass this information as a state in the request)</li><li>we prepare the authentication URL for Google OAuth</li><li>we display a login button in the telegram chat so user can click to login in Google</li></ul><pre>  bot.command(&#39;login&#39;, async (ctx) =&gt; {<br>   const state = crypto.randomUUID();<br>   const chatId = ctx.chat.id.toString();<br><br>   // Store state in KV with 5 minute expiration<br>   await env.OAUTH_STATES.put(state, chatId, {<br>    expirationTtl: 300,<br>   });<br><br>   const authUrl = new URL(&#39;https://accounts.google.com/o/oauth2/v2/auth&#39;);<br>   authUrl.searchParams.append(&#39;client_id&#39;, env.GOOGLE_CLIENT_ID);<br>   authUrl.searchParams.append(&#39;redirect_uri&#39;, env.OAUTH_REDIRECT_URI);<br>   authUrl.searchParams.append(&#39;response_type&#39;, &#39;code&#39;);<br>   authUrl.searchParams.append(&#39;scope&#39;, &#39;https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events&#39;);<br>   authUrl.searchParams.append(&#39;state&#39;, state);<br>   authUrl.searchParams.append(&#39;access_type&#39;, &#39;offline&#39;);<br><br>   await ctx.reply(&#39;Please authenticate with Google to use this bot:&#39;, {<br>    reply_markup: {<br>     inline_keyboard: [[{ text: &#39;Login with Google&#39;, url: authUrl.toString() }]],<br>    },<br>   });<br>  });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*wy0A_oxtuyDHnNfxfEFMRA.png" /></figure><p>when you click on the Login button, you browser will open with the authentication URL requesting access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l2XV6ttQyaeO6E2YUDF2A.png" /><figcaption>OAuth screen</figcaption></figure><p>We now define a method that will handle the response from Google (the URL must match the value from OATH_REDIRECT_URI parameter.</p><p>We check that we received the state so we can retrieve the chatId from the KV store and then remove (we did add a 5 min expiration so it will anyway get removed) and then using the code given from the callback we can get the OAuth token by adding our google client data. We store the token in another KV store and associate that with our chatId so we can reuse later in the same chat.</p><pre><br>  if (request.url.includes(&#39;/api/auth/callback/google&#39;)) {<br>   const url = new URL(request.url);<br>   const code = url.searchParams.get(&#39;code&#39;);<br>   const state = url.searchParams.get(&#39;state&#39;);<br><br>   if (!code || !state) {<br>    return new Response(&#39;Missing code or state&#39;, { status: 400 });<br>   }<br><br>   // Get chatId from KV<br>   const chatId = await env.OAUTH_STATES.get(state);<br>   if (!chatId) {<br>    return new Response(&#39;Invalid or expired chat&#39;, { status: 400 });<br>   }<br><br>   // Delete the state from KV as it&#39;s no longer needed<br>   await env.OAUTH_STATES.delete(state);<br><br>   // Exchange code for tokens<br>   const tokenResponse = await fetch(&#39;https://oauth2.googleapis.com/token&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>     &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>    },<br>    body: new URLSearchParams({<br>     code,<br>     client_id: env.GOOGLE_CLIENT_ID,<br>     client_secret: env.GOOGLE_CLIENT_SECRET,<br>     redirect_uri: env.OAUTH_REDIRECT_URI,<br>     grant_type: &#39;authorization_code&#39;,<br>    }),<br>   });<br><br>   const tokenData = await tokenResponse.json();<br><br>   // Store the token in a token KV<br>   await env.OAUTH_TOKEN.put(chatId, JSON.stringify(tokenData));<br><br>   await bot.api.sendMessage(chatId, &#39;Successfully authenticated! You can now use the bot.&#39;);<br>   return new Response(&#39;Authentication successful! You can close this window.&#39;);<br>  }</pre><p>We will now be able to implement any other command; we can just implement a <a href="https://grammy.dev/guide/middleware">middleware</a> so any further command defined in the file will require to be authenticated and will return an error message if we cannot find a valid token associated with the chatId.</p><pre>  // Middleware to check authentication<br>  bot.use(async (ctx, next) =&gt; {<br>   if (!ctx.chat || !ctx.chat.id) {<br>    await ctx.reply(&#39;Please restart the chat&#39;);<br>    return;<br>   }<br><br>   const chatId = ctx.chat.id.toString();<br>   const token = await env.OAUTH_TOKEN.get(chatId);<br>   if (!token &amp;&amp; ctx.message?.text !== &#39;/login&#39;) {<br>    await ctx.reply(&#39;Please authenticate first using /login&#39;);<br>    return;<br>   }<br>   await next();<br>  });</pre><p>Dont forget at the end of the middleware to call next() otherwise the command will not be triggered.</p><p>Then we can implement a basic command against the Google Calendar API just to make sure everything is working correctly</p><pre>  bot.command(&#39;calendar&#39;, async (ctx) =&gt; {<br>   await ctx.reply(&#39;Getting list of calendar&#39;);<br><br>   const chatId = ctx.chat.id.toString();<br>   const token = await env.OAUTH_TOKEN.get(chatId);<br>   const accessToken = token ? JSON.parse(token).access_token : null;<br><br>   try {<br>    const response = await fetch(&#39;https://www.googleapis.com/calendar/v3/users/me/calendarList&#39;, {<br>     headers: {<br>      Authorization: `Bearer ${accessToken}`,<br>      &#39;Cache-Control&#39;: &#39;no-cache&#39;,<br>     },<br>    });<br><br>    if (response.status === 401) {<br>     await env.OAUTH_TOKEN.delete(chatId);<br>     await ctx.reply(&#39;Your session has expired. Please authenticate again using /login.&#39;);<br>     return;<br>    }<br><br>    const data = (await response.json()) as calendar_v3.Schema$CalendarList;<br><br>    // Format the calendar items into a table-like string<br>    let message = &#39;📅 *Your Calendars*\n\n&#39;;<br><br>    if (data.items) {<br>     data.items.forEach((calendar, index) =&gt; {<br>      message += `*${index + 1}. ${calendar.summary}*\n`;<br>      if (calendar.description) {<br>       // Truncate description if too long<br>       const desc = calendar.description.length &gt; 50 ? calendar.description.substring(0, 47) + &#39;...&#39; : calendar.description;<br>       message += `📝 ${desc}\n`;<br>      }<br>      message += `🌍 ${calendar.timeZone}\n\n`;<br>     });<br><br>     // Split message if it&#39;s too long for Telegram<br>     if (message.length &gt; 4096) {<br>      const chunks = message.match(/.{1,4096}/g) || [];<br>      for (const chunk of chunks) {<br>       await ctx.reply(chunk, { parse_mode: &#39;Markdown&#39; });<br>      }<br>     } else {<br>      await ctx.reply(message, { parse_mode: &#39;Markdown&#39; });<br>     }<br>    }<br>   } catch (error) {<br>    await env.OAUTH_TOKEN.delete(chatId);<br>    await ctx.reply(&#39;Error fetching calendars. Please try authenticating again with /login&#39;);<br>   }<br>  });</pre><p>And this will display the list of your current Google calendar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*L5ocHEctkAa-EuIPsBoAxA.png" /></figure><p>Now you can interract with Google APIs within your bot. You could do the same for any service that uses OAuth authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0003764e83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom CSS Animation in NextJS / Tailwind project for backend devs.]]></title>
            <link>https://medium.com/@frederic.henri/custom-css-animation-in-nextjs-tailwind-project-for-backend-devs-88add0b05ea9?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/88add0b05ea9</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-animation]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 12:49:55 GMT</pubDate>
            <atom:updated>2024-11-28T12:49:55.916Z</atom:updated>
            <content:encoded><![CDATA[<p>I will build my landing page for my custom finance application using tailwind and CSS animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTcYMRZDE6wgipcQjZCClA.png" /><figcaption>landing page screenshot</figcaption></figure><p>As a fullstack developer, I often have to work on UI, generally coming from figma design. <a href="https://tailwindcss.com/">Tailwind-css</a> has come to rescue multiple times (specially due to its neat integration with NextJS) and library components like <a href="https://ui.shadcn.com/">shadcn/ui</a> often do the trick to get a working UI.</p><p>However for a landing page, I wanted to integrate some animation, so mainly we’ll have 2 sections of the page with animation:</p><ul><li>First, we have a screenshot of the app that starts with an inclined position and will rotate like if you’re opening a laptop and will remain horizontally visible.</li><li>Second, we’ll have feature list displayed with animation when the user scrolls enough in the page.</li></ul><p>We’ll integrate the landing page into an <a href="https://github.com/fhenri/pfm">existing NextJS application</a>, for now we’ll work with tailwind 3.x and I’ll probably revisit this article once tailwind 4 will be out and will provide some implementation for animation properties.</p><h3>Main page</h3><p>As we mentioned we’ll have mainly 2 animations so we’ll create 2 components for each animation and the skeleton of the page will look like</p><ul><li>For the 1st part</li></ul><pre>      &lt;main className=&quot;flex items-center bg-white dark:bg-gray-800&quot;&gt;<br>        &lt;div className=&quot;container flex flex-col items-center justify-between px-6 py-8 mx-auto&quot;&gt;<br>          &lt;div className=&quot;flex flex-col py-24&quot;&gt;<br>            &lt;h1 className=&quot;w-full text-4xl font-light text-center text-gray-800 uppercase sm:text-5xl dark:text-white mt-6&quot;&gt;<br>              Take control of your Personal Finance<br>            &lt;/h1&gt;<br>            &lt;h2 className=&quot;w-full max-w-2xl py-8 mt-6 mx-auto text-4xl font-bold text-center&quot;&gt;<br>              &lt;p className=&quot;bg-clip-text bg-gradient-to-r from-red-500 to-green-500 text-transparent uppercase&quot;&gt;<br>                Personal Finance Manager<br>              &lt;/p&gt;<br>            &lt;/h2&gt;<br>          &lt;/div&gt;<br>          &lt;ImageAnimation /&gt;<br>        &lt;/div&gt;<br>      &lt;/main&gt;</pre><ul><li>For the 2nd part</li></ul><pre>      &lt;section className=&quot;py-12 &quot;&gt;<br>        &lt;div className=&quot;mx-auto max-w-7xl px-4 sm:px-6 lg:px-8&quot;&gt;<br>              &lt;div className=&quot;mb-10 lg:mb-16 flex justify-center items-center flex-col gap-x-0 gap-y-6 lg:gap-y-0 lg:flex-row lg:justify-between max-md:max-w-lg max-md:mx-auto&quot;&gt;<br>                  &lt;div className=&quot;relative w-full text-center lg:text-left lg:w-2/4&quot;&gt;<br>                      &lt;h2 className=&quot;text-4xl font-bold text-gray-900 leading-[3.25rem] lg:mb-6 mx-auto max-w-max lg:max-w-md lg:mx-0&quot;&gt;Enjoy the finest features with this product&lt;/h2&gt;<br>                  &lt;/div&gt;<br>                  &lt;div className=&quot;relative w-full text-center  lg:text-left lg:w-2/4&quot;&gt;<br>                      &lt;p className=&quot;text-lg font-normal text-gray-500 mb-5&quot;&gt;We provide all the advantages that can simplify all your financial life without any further requirements&lt;/p&gt; <br>                  &lt;/div&gt;<br>              &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;FeatureAnimation/&gt;<br>      &lt;/section&gt;</pre><h3>Scrolling event animation</h3><p>First, we’ll create the ImageAnimation component. The component will display the image and we will apply some effects</p><pre>    &lt;div <br>      className=&quot;block w-full mx-auto mt-6 md:mt-24&quot;&gt;<br>      &lt;Image<br>        className=&quot;dark:invert max-w-xs m-auto md:max-w-4xl border-gradient&quot;<br>        src=&quot;/screenshot/main.webp&quot;<br>        alt=&quot;PFM Screenshot&quot;<br>        width={1200}<br>        height={693}<br>        priority<br>      /&gt;<br>    &lt;/div&gt;</pre><p>We want to have an effect when user scrolls the page so we need to add an event listener on this scroll event, somewhere in our code we need to add window.addEventListener(&#39;scroll&#39;, callback_when_scroll)</p><p>In React we need to declare this within an <a href="https://react.dev/learn/synchronizing-with-effects#subscribing-to-events">useEffect()</a> hook so we’ll get the following</p><pre>const ImageAnimation = () =&gt; {<br><br>  useEffect(() =&gt; {<br><br>    const handleScroll = () =&gt; {<br>    .... // logic to implement when we scroll<br>    };<br><br>    // Add scroll event listener<br>    window.addEventListener(&#39;scroll&#39;, handleScroll);<br>    // Initial call to set correct angle on load<br>    //handleScroll();<br><br>    return () =&gt; {<br>        window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    };<br>  }, []);<br>  ...<br>}</pre><p>we know we will need to apply <a href="https://nextjs.org/docs/pages/api-reference/components/image#style">custom style</a> on the image and we need to rotate the image with a certain angle. The angle will be defined in the handleScroll method and will set a state, this state will be applied in the image style. That will give something like</p><pre>const ImageAnimation = () =&gt; {<br><br>  const [angle, setAngle] = useState(&quot;-30deg&quot;); // we start with -30° rotation<br><br>  useEffect(() =&gt; {<br><br>    const handleScroll = () =&gt; {<br>    .... // calculate the angle to apply<br>    };<br><br>    // Add scroll event listener<br>    window.addEventListener(&#39;scroll&#39;, handleScroll);<br>    // Initial call to set correct angle on load<br>    //handleScroll();<br><br>    return () =&gt; {<br>        window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div <br>      className=&quot;block w-full mx-auto mt-6 md:mt-24&quot;&gt;<br>      &lt;Image<br>        className=&quot;dark:invert max-w-xs m-auto md:max-w-4xl border-gradient&quot;<br>        style={{ <br>          transform: `perspective(800px) rotateX(${angle}))`,<br>        }} <br>        src=&quot;/screenshot/main.webp&quot;<br>        alt=&quot;PFM Screenshot&quot;<br>        width={1200}<br>        height={693}<br>        priority<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>we can try at this time to test and set some angle default value in the handleScroll method just to see if it works, it will rotate the image but will not have smooth rotation.</p><h4>Let’s run some math</h4><p>To get something nice to run, we need to apply the angle based on the visibility of the image, so we’ll check how much part of the image is visible in the viewport (we’ll run the rotation once the image is 33% visible). To do our math propertly and determined if the image (and how much) is in viewport, we need to have some reference of the HTML elements, so we’ll add useRef on the div and imag element and we’ll be able to use them in the effect:</p><pre>const ImageAnimation = () =&gt; {<br>  const imageRef = useRef&lt;HTMLImageElement | null&gt;(null);<br>  const containerRef = useRef&lt;HTMLDivElement | null&gt;(null);<br><br>  const [angle, setAngle] = useState(&quot;-30deg&quot;); // we start with -30° rotation<br><br>  useEffect(() =&gt; {<br>    const imageElement = ref.current;<br>    const containerElement = containerRef.current;<br>    if (!imageElement || !containerElement) return;<br><br>    const handleScroll = () =&gt; {<br>      // Get the bounding rectangle of the image<br>      const rect = imageElement.getBoundingClientRect();<br>      <br>      // Get viewport height<br>      const viewportHeight = window.innerHeight;<br><br>      // Check if the image is actually in the viewport<br>      const isInViewport = <br>        rect.top &lt; viewportHeight &amp;&amp; <br>        rect.bottom &gt; 0;<br><br>      // If not in viewport, don&#39;t change angle<br>      if (!isInViewport) {<br>        return;<br>      }<br><br>      // Calculate how much of the image is in the viewport<br>      const visibleHeight = Math.min(rect.bottom, viewportHeight) - Math.max(rect.top, 0);<br>      <br>      // Calculate the percentage of the image visible<br>      const visiblePercentage = visibleHeight / rect.height;<br><br>      if (visiblePercentage &gt;= 0.33 &amp;&amp; visiblePercentage &lt;= 1 &amp;&amp; rect.top &gt; 0) {<br>        // Linear interpolation from -30 to 0 degrees<br>        const normalizedRatio = (visiblePercentage - 0.33) / (1 - 0.33);<br>        const newAngle = -30 + (normalizedRatio * 30);<br>        setAngle(`${newAngle.toFixed(1)}deg`);<br>    };<br><br>    // Add scroll event listener<br>    window.addEventListener(&#39;scroll&#39;, handleScroll);<br>    // Initial call to set correct angle on load<br>    //handleScroll();<br><br>    return () =&gt; {<br>        window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div <br>      ref={containerRef}<br>      className=&quot;block w-full mx-auto mt-6 md:mt-24&quot;&gt;<br>      &lt;Image<br>        ref={imageRef}<br>        className=&quot;dark:invert max-w-xs m-auto md:max-w-4xl border-gradient&quot;<br>        style={{ <br>          transform: `perspective(800px) rotateX(${angle}))`,<br>        }} <br>        src=&quot;/screenshot/main.webp&quot;<br>        alt=&quot;PFM Screenshot&quot;<br>        width={1200}<br>        height={693}<br>        priority<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>with that we get a nice effect when we scroll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ql75q0DLr0sL87uJXq0WQ.gif" /><figcaption>scroll effect</figcaption></figure><h3>Intersection observer pattern</h3><p>Next we’ll want to add an effect when the user has scrolled the page and some element will get added in the page. This sounds like the definition of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">intersection observer pattern</a></p><blockquote>The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/Viewport">viewport</a>.</blockquote><blockquote>Intersection information is needed for many reasons, such as:</blockquote><blockquote>- Lazy-loading of images or other content as a page is scrolled</blockquote><p>so we start by definition the feature animation component and adding one feature:</p><pre>const FeatureAnimation = () =&gt; {<br>  return (<br>    &lt;div className=&quot;flex justify-center items-center gap-x-5 gap-y-8 lg:gap-y-0 flex-wrap md:flex-wrap lg:flex-nowrap lg:flex-row lg:justify-between lg:gap-x-8&quot;&gt;<br>        &lt;div className=&quot;group relative w-full bg-gray-100 rounded-2xl p-4 max-md:max-w-md max-md:mx-auto <br>            md:w-2/5 md:h-64 xl:p-7 xl:w-1/4 perspective-1000&quot;&gt;<br>            &lt;div className=&quot;flex flex-col justify-center p-4&quot;&gt;<br>              &lt;div className=&quot;bg-white rounded-full flex justify-center items-center mb-5 w-14 h-14&quot;&gt;<br>                      &lt;svg<br>                        width=&quot;30&quot;<br>                        height=&quot;30&quot;<br>                        viewBox=&quot;0 0 30 30&quot;<br>                        fill=&quot;none&quot;<br>                        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>                      &gt;<br>                        &lt;path<br>                          d=&quot;M24.7222 11.6667V7.22225C24.7222 5.99495 23.7273 5 22.5 5H4.72222C3.49492 5 2.5 5.99492 2.5 7.22222V22.7778C2.5 24.0051 3.49492 25 4.72222 25H22.5C23.7273 25 24.7222 24.005 24.7222 22.7777V17.7778M20.8333 17.7778H25.2778C26.5051 17.7778 27.5 16.7829 27.5 15.5556V13.8889C27.5 12.6616 26.5051 11.6667 25.2778 11.6667H20.8333C19.606 11.6667 18.6111 12.6616 18.6111 13.8889V15.5556C18.6111 16.7829 19.606 17.7778 20.8333 17.7778Z&quot;<br>                          stroke=&quot;#4F46E5&quot;<br>                          strokeWidth=&quot;2&quot;<br>                        &gt;&lt;/path&gt;<br>                      &lt;/svg&gt;<br>              &lt;/div&gt;<br>              &lt;h4 className=&quot;text-xl font-semibold text-gray-900 mb-3 capitalize &quot;&gt;<br>                Multi currency<br>              &lt;/h4&gt;<br>              &lt;p className=&quot;text-sm font-normal text-gray-500 leading-5&quot;&gt;<br>                Integrating with &lt;a href=&#39;https://currencyapi.com/&#39;&gt;https://currencyapi.com/&lt;/a&gt; to get daily rates and adjusted rate of the transaction day<br>              &lt;/p&gt;<br>            &lt;/div&gt;<br><br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FeatureAnimation;</pre><p>We can work with some AI generated text (chatGPT) to generate some marketing text and we figure we can add features in array and loop through the array to place the feature text on screen</p><pre>const features = [<br>  {<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M24.7222 11.6667V7.22225C24.7222 5.99495 23.7273 5 22.5 5H4.72222C3.49492 5 2.5 5.99492 2.5 7.22222V22.7778C2.5 24.0051 3.49492 25 4.72222 25H22.5C23.7273 25 24.7222 24.005 24.7222 22.7777V17.7778M20.8333 17.7778H25.2778C26.5051 17.7778 27.5 16.7829 27.5 15.5556V13.8889C27.5 12.6616 26.5051 11.6667 25.2778 11.6667H20.8333C19.606 11.6667 18.6111 12.6616 18.6111 13.8889V15.5556C18.6111 16.7829 19.606 17.7778 20.8333 17.7778Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Multi currency&quot;,<br>    description:<br>      &quot;Integrating with &lt;a href=&#39;https://currencyapi.com/&#39;&gt;https://currencyapi.com/&lt;/a&gt; to get daily rates and adjusted rate of the transaction day&quot;,<br>  },<br>  {<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M14.375 15.8571C16.1009 15.8571 17.5 14.458 17.5 12.7321C17.5 11.0062 16.1009 9.6071 14.375 9.6071C12.6491 9.6071 11.25 11.0062 11.25 12.7321C11.25 14.458 12.6491 15.8571 14.375 15.8571ZM14.375 15.8571V20.8571M3.75 13.2264V15.2343C3.75 17.6868 3.75 18.9131 4.27747 19.9685C4.80493 21.0239 5.78567 21.76 7.74715 23.2322L8.57248 23.8516C11.4626 26.0208 12.9077 27.1054 14.5753 27.1054C16.243 27.1054 17.688 26.0208 20.5782 23.8516L21.4035 23.2322C23.365 21.76 24.3457 21.0239 24.8732 19.9685C25.4006 18.9131 25.4006 17.6868 25.4006 15.2343V13.2264C25.4006 9.95932 25.4006 8.32576 24.546 7.05852C23.6913 5.79128 22.1768 5.17918 19.1477 3.95499L18.3223 3.62144C16.4724 2.87381 15.5475 2.5 14.5753 2.5C13.6032 2.5 12.6782 2.87381 10.8283 3.62144L10.003 3.95499C6.97389 5.17919 5.45934 5.79128 4.60467 7.05852C3.75 8.32576 3.75 9.95932 3.75 13.2264Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Import Transaction&quot;,<br>    description:<br>      &quot;Import from any bank supporting standard file export. Custom File Import can be developed for exotic bank account.&quot;,<br>  },<br>  {<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M15.0067 10V15.6652C15.0067 16.0358 15.1712 16.3873 15.4556 16.6248L18.75 19.375M15 27.5C8.09644 27.5 2.5 21.9036 2.5 15C2.5 8.09644 8.09644 2.5 15 2.5C21.9036 2.5 27.5 8.09644 27.5 15C27.5 21.9036 21.9036 27.5 15 27.5Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Automatic Spend Categorization&quot;,<br>    description:<br>      &quot;Spend is categorized based on previous transactions and your custom rules.&quot;,<br>  },<br>  {<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M10 14.7875L13.0959 17.8834C13.3399 18.1274 13.7353 18.1275 13.9794 17.8838L20.625 11.25M15 27.5C8.09644 27.5 2.5 21.9036 2.5 15C2.5 8.09644 8.09644 2.5 15 2.5C21.9036 2.5 27.5 8.09644 27.5 15C27.5 21.9036 21.9036 27.5 15 27.5Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Custom Dashboard&quot;,<br>    description:<br>      &quot;We provide dashboard and analysis on your spend so you can further analyze where the money comes and goes.&quot;,<br>  },<br>];<br><br>  return (<br>    &lt;div<br>      ref={containerRef}<br>      className=&quot;flex justify-center items-center gap-x-5 gap-y-8 lg:gap-y-0 flex-wrap md:flex-wrap lg:flex-nowrap lg:flex-row lg:justify-between lg:gap-x-8&quot;<br>    &gt;<br>      {features.map((feature, index) =&gt; (<br>        &lt;div<br>          key={feature.title}<br>          className=&quot;group relative w-full bg-gray-100 rounded-2xl p-4 max-md:max-w-md max-md:mx-auto <br>            md:w-2/5 md:h-64 xl:p-7 xl:w-1/4 perspective-1000&quot;&gt;<br>            &lt;div className=&quot;flex flex-col justify-center p-4&quot;&gt;<br>              &lt;div className=&quot;bg-white rounded-full flex justify-center items-center mb-5 w-14 h-14&quot;&gt;<br>                {feature.icon}<br>              &lt;/div&gt;<br>              &lt;h4 className=&quot;text-xl font-semibold text-gray-900 mb-3 capitalize &quot;&gt;<br>                {feature.title}<br>              &lt;/h4&gt;<br>              &lt;p className=&quot;text-sm font-normal text-gray-500 leading-5&quot;<br>                 dangerouslySetInnerHTML={{__html: feature.description}}&gt;<br>              &lt;/p&gt;<br>            &lt;/div&gt;<br><br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FeatureAnimation;</pre><p>Note we’ll use <a href="https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html">dangerouslySetInnerHTML</a> as some of our content contains HTML anchor element.</p><p>Now we’ve got the sketch up to play, we can introduce some CSS effect.</p><p>We want to display the first card when the div is lets say 30% within the viewport and then we want to display the rest of the feature one after the other.</p><p>So we need the intersection observer to detect one we should trigger the first feature, and the other feature will just have a delay. We can add the delay duration in the features array.</p><p>We can define an array of visible features so we know which one to display, when the entry is within the viewport with our threshold we kick off the feature to be visible and after for each feature we’ll have them visible after a delay (that can vary for each feature)</p><pre>const FeatureAnimation = () =&gt; {<br>  const containerRef = useRef&lt;HTMLDivElement | null&gt;(null);<br>  const [visibleFeatures, setVisibleFeatures] = useState&lt;boolean[]&gt;(<br>    new Array(features.length).fill(false)<br>  );<br><br>  useEffect(() =&gt; {<br>    const observer = new IntersectionObserver(<br>      (entries) =&gt; {<br>        entries.forEach((entry) =&gt; {<br>          if (entry.isIntersecting) {<br>            // When the container becomes visible, start staggered animation<br>            const newVisibleFeatures = [...visibleFeatures];<br><br>            features.forEach((feature, index) =&gt; {<br>              setTimeout(() =&gt; {<br>                newVisibleFeatures[index] = true;<br>                setVisibleFeatures([...newVisibleFeatures]);<br>              }, index * feature.duration);<br>            });<br><br>            // Stop observing once the animation is triggered<br>            observer.unobserve(entry.target);<br>          }<br>        });<br>      },<br>      {<br>        root: null, // viewport<br>        rootMargin: &quot;0px&quot;,<br>        threshold: [0.5, 1],<br>      }<br>    );<br><br>    if (containerRef.current) {<br>      observer.observe(containerRef.current);<br>    }<br><br>    return () =&gt; {<br>      observer.disconnect();<br>    };<br>  }, []);</pre><p>Based on this state, we can adapt the rendered HTML to display the feature or not</p><pre>  return (<br>    &lt;div<br>      ref={containerRef}<br>      className=&quot;flex justify-center items-center gap-x-5 gap-y-8 lg:gap-y-0 flex-wrap md:flex-wrap lg:flex-nowrap lg:flex-row lg:justify-between lg:gap-x-8&quot;<br>    &gt;<br>      {features.map((feature, index) =&gt; (<br>        &lt;div<br>          key={feature.title}<br>          className={`<br>            group relative w-full bg-gray-100 rounded-2xl p-4 max-md:max-w-md max-md:mx-auto <br>            md:w-2/5 md:h-64 xl:p-7 xl:w-1/4 perspective-1000<br>            ${<br>              visibleFeatures[index]<br>                ? &quot;scale-100 opacity-100&quot;<br>                : &quot;scale-95 opacity-0&quot;<br>            }<br>          `}<br>          &gt;<br>          &lt;div<br>            className=&quot;inset-0 backface-hidden flex flex-col justify-center p-4&quot;<br>          &gt;<br>            &lt;div className=&quot;bg-white rounded-full flex justify-center items-center mb-5 w-14 h-14&quot;&gt;<br>              {feature.icon}<br>            &lt;/div&gt;<br>            &lt;h4 className=&quot;text-xl font-semibold text-gray-900 mb-3 capitalize &quot;&gt;<br>              {feature.title}<br>            &lt;/h4&gt;<br>            &lt;p<br>              className=&quot;text-sm font-normal text-gray-500 leading-5&quot;<br>              dangerouslySetInnerHTML={{__html: feature.description}}<br>            &gt;                <br>            &lt;/p&gt;<br>          &lt;/div&gt;<br><br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FeatureAnimation;</pre><p>so now when we scroll down to the page, we have the features displayed one by one, “tac ….. tac …. tac … tac”</p><p>This is cool (even thoug we do that at the end of the page so in term of rendering we could have done better, but hey this is mainly a sandbox and testing the implementation of the pattern)</p><p>Next thing we could do is to to be able to flip the feature card so it reveals a screenshot, we can add the screenshot in the features array (as well as the duration we discussed before)</p><pre>const features = [<br>  {<br>    duration: 0,<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M24.7222 11.6667V7.22225C24.7222 5.99495 23.7273 5 22.5 5H4.72222C3.49492 5 2.5 5.99492 2.5 7.22222V22.7778C2.5 24.0051 3.49492 25 4.72222 25H22.5C23.7273 25 24.7222 24.005 24.7222 22.7777V17.7778M20.8333 17.7778H25.2778C26.5051 17.7778 27.5 16.7829 27.5 15.5556V13.8889C27.5 12.6616 26.5051 11.6667 25.2778 11.6667H20.8333C19.606 11.6667 18.6111 12.6616 18.6111 13.8889V15.5556C18.6111 16.7829 19.606 17.7778 20.8333 17.7778Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Multi currency&quot;,<br>    description:<br>      &quot;Integrating with &lt;a href=&#39;https://currencyapi.com/&#39;&gt;https://currencyapi.com/&lt;/a&gt; to get daily rates and adjusted rate of the transaction day&quot;,<br>    screenshot: &quot;feature-multi-currency.png&quot;,<br>  },<br>  {<br>    duration: 800,<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M14.375 15.8571C16.1009 15.8571 17.5 14.458 17.5 12.7321C17.5 11.0062 16.1009 9.6071 14.375 9.6071C12.6491 9.6071 11.25 11.0062 11.25 12.7321C11.25 14.458 12.6491 15.8571 14.375 15.8571ZM14.375 15.8571V20.8571M3.75 13.2264V15.2343C3.75 17.6868 3.75 18.9131 4.27747 19.9685C4.80493 21.0239 5.78567 21.76 7.74715 23.2322L8.57248 23.8516C11.4626 26.0208 12.9077 27.1054 14.5753 27.1054C16.243 27.1054 17.688 26.0208 20.5782 23.8516L21.4035 23.2322C23.365 21.76 24.3457 21.0239 24.8732 19.9685C25.4006 18.9131 25.4006 17.6868 25.4006 15.2343V13.2264C25.4006 9.95932 25.4006 8.32576 24.546 7.05852C23.6913 5.79128 22.1768 5.17918 19.1477 3.95499L18.3223 3.62144C16.4724 2.87381 15.5475 2.5 14.5753 2.5C13.6032 2.5 12.6782 2.87381 10.8283 3.62144L10.003 3.95499C6.97389 5.17919 5.45934 5.79128 4.60467 7.05852C3.75 8.32576 3.75 9.95932 3.75 13.2264Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Import Transaction&quot;,<br>    description:<br>      &quot;Import from any bank supporting standard file export. Custom File Import can be developed for exotic bank account.&quot;,<br>    screenshot: &quot;feature-import.png&quot;,<br>  },<br>  {<br>    duration: 500,<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M15.0067 10V15.6652C15.0067 16.0358 15.1712 16.3873 15.4556 16.6248L18.75 19.375M15 27.5C8.09644 27.5 2.5 21.9036 2.5 15C2.5 8.09644 8.09644 2.5 15 2.5C21.9036 2.5 27.5 8.09644 27.5 15C27.5 21.9036 21.9036 27.5 15 27.5Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Automatic Spend Categorization&quot;,<br>    description:<br>      &quot;Spend is categorized based on previous transactions and your custom rules.&quot;,<br>    screenshot: &quot;feature-category.png&quot;,<br>  },<br>  {<br>    duration: 400,<br>    icon: (<br>      &lt;svg<br>        width=&quot;30&quot;<br>        height=&quot;30&quot;<br>        viewBox=&quot;0 0 30 30&quot;<br>        fill=&quot;none&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      &gt;<br>        &lt;path<br>          d=&quot;M10 14.7875L13.0959 17.8834C13.3399 18.1274 13.7353 18.1275 13.9794 17.8838L20.625 11.25M15 27.5C8.09644 27.5 2.5 21.9036 2.5 15C2.5 8.09644 8.09644 2.5 15 2.5C21.9036 2.5 27.5 8.09644 27.5 15C27.5 21.9036 21.9036 27.5 15 27.5Z&quot;<br>          stroke=&quot;#4F46E5&quot;<br>          strokeWidth=&quot;2&quot;<br>          strokeLinecap=&quot;round&quot;<br>          strokeLinejoin=&quot;round&quot;<br>        &gt;&lt;/path&gt;<br>      &lt;/svg&gt;<br>    ),<br>    title: &quot;Custom Dashboard&quot;,<br>    description:<br>      &quot;We provide dashboard and analysis on your spend so you can further analyze where the money comes and goes.&quot;,<br>    screenshot: &quot;feature-dashboard.png&quot;,<br>  },<br>];</pre><p>We add a state as an array of which feature is currently ‘flipped’, we need one method to toggle the card and we add the event on the mouse hover the card, the effect is well described on this page <a href="https://www.w3schools.com/howto/howto_css_flip_card.asp">https://www.w3schools.com/howto/howto_css_flip_card.asp</a> and we just do the NextJS implementation here:</p><pre>const FeatureAnimation = () =&gt; {<br>  const containerRef = useRef&lt;HTMLDivElement | null&gt;(null);<br>  const [visibleFeatures, setVisibleFeatures] = useState&lt;boolean[]&gt;(<br>    new Array(features.length).fill(false)<br>  );<br>  const [flippedFeatures, setFlippedFeatures] = useState&lt;boolean[]&gt;(<br>    new Array(features.length).fill(false)<br>  );<br><br>  ....<br><br>  const toggleFlip = (index: number) =&gt; {<br>    const newFlippedFeatures = [...flippedFeatures];<br>    newFlippedFeatures[index] = !newFlippedFeatures[index];<br>    setFlippedFeatures(newFlippedFeatures);<br>  };<br><br>  return (<br>    &lt;div<br>      ref={containerRef}<br>      className=&quot;flex justify-center items-center gap-x-5 gap-y-8 lg:gap-y-0 flex-wrap md:flex-wrap lg:flex-nowrap lg:flex-row lg:justify-between lg:gap-x-8&quot;<br>    &gt;<br>      {features.map((feature, index) =&gt; (<br>        &lt;div<br>          key={feature.title}<br>          onMouseEnter={() =&gt; toggleFlip(index)}<br>          onMouseLeave={() =&gt; toggleFlip(index)}<br>          className={`<br>            group relative w-full bg-gray-100 rounded-2xl p-4 max-md:max-w-md max-md:mx-auto <br>            md:w-2/5 md:h-64 xl:p-7 xl:w-1/4 perspective-1000<br>            ${<br>              visibleFeatures[index]<br>                ? &quot;scale-100 opacity-100&quot;<br>                : &quot;scale-95 opacity-0&quot;<br>            }<br>          `}<br>          &gt;<br>          {/* This container is needed to position the front and back side */}<br>          {/* https://www.w3schools.com/howto/howto_css_flip_card.asp */}<br>          &lt;div className={`<br>            flip-card-inner <br>            ${flippedFeatures[index] ? &quot;flip-card&quot; : &quot;&quot;}<br>          `}&gt;<br>            {/* Front Side */}<br>            &lt;div<br>              className={`<br>              absolute inset-0 backface-hidden flex flex-col justify-center p-4<br>              ${flippedFeatures[index] ? &quot;hidden&quot; : &quot;block&quot;}<br>            `}<br>            &gt;<br>              &lt;div className=&quot;bg-white rounded-full flex justify-center items-center mb-5 w-14 h-14&quot;&gt;<br>                {feature.icon}<br>              &lt;/div&gt;<br>              &lt;h4 className=&quot;text-xl font-semibold text-gray-900 mb-3 capitalize &quot;&gt;<br>                {feature.title}<br>              &lt;/h4&gt;<br>              &lt;p<br>                className={`text-sm font-normal text-gray-500 leading-5<br>                ${<br>                  visibleFeatures[index]<br>                    ? &quot;opacity-100 translate-y-0&quot;<br>                    : &quot;opacity-0 translate-y-5&quot;<br>                }<br>                transition-all duration-700 ease-out delay-500`}<br>                dangerouslySetInnerHTML={{__html: feature.description}}<br>              &gt;<br>                <br>              &lt;/p&gt;<br>            &lt;/div&gt;<br><br>            {/* Back Side (Screenshot) */}<br>            &lt;div<br>              className={`<br>              absolute inset-0 backface-hidden rotate-y-180 <br>              flex items-center justify-center <br>              ${flippedFeatures[index] ? &quot;block&quot; : &quot;hidden&quot;}<br>            `}<br>            &gt;<br>              &lt;Image<br>                src={`/screenshot/${feature.screenshot}`}<br>                alt={`${feature.title} screenshot`}<br>                width={1024}<br>                height={1024}<br>                className=&quot;max-w-full max-h-full object-contain rounded-lg shadow-lg flip-card&quot;<br>              /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FeatureAnimation;</pre><p>To simplify the CSS we do add the following property in global.css so we can reuse as-is in the html</p><pre>@layer components {<br><br>    .border-gradient {<br>        border-style: solid;<br>        border-width: 2px;<br>        border-image: linear-gradient(90deg, #DC2626, #84cc16) 1;<br>        perspective-origin: top;<br>    }<br><br>    .flip-card {<br>        transform: rotateY(180deg);<br>    }<br><br>    .flip-card-inner {<br>        position: relative;<br>        width: 100%;<br>        height: 100%;<br>        text-align: center;<br>        transition: transform 0.8s;<br>        transform-style: preserve-3d;<br>    }<br>}</pre><p>This produces the following effect and a screenshot will display in the feature card when hovering with the mouse</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnjJBOZcxZ5QzOX2PRWCcQ.gif" /></figure><p>So lets be clear, this page will not impressed any UI/X Web Designer but the mechanism explains here can drive a lot of animation we see on site. There’s much more on animation and soon we’ll have tailwind shipped some <a href="https://tailwindcss.com/docs/v4-beta#configuring-animations-and-keyframes">default animation</a>, you could also explore <a href="https://motion.dev/">motion</a> or if you want to use a broader lib you can look at <a href="https://gsap.com/">GSAP</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88add0b05ea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to React-Native: Build a Form and integrate with API backend]]></title>
            <link>https://medium.com/@frederic.henri/introduction-to-react-native-build-a-form-and-integrate-with-api-backend-ea72b4963a23?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea72b4963a23</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 12:32:09 GMT</pubDate>
            <atom:updated>2024-11-22T12:32:09.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to create a simple app for mobile, we will use the popular <a href="https://reactnative.dev/">react native</a> framework to ease the development of native mobile app.</p><p>Our sample app will be a single page form app that will ask users user to fill some information and will work with the <a href="https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-i-2393a80a70d0">meeting API</a> we already discussed and check for available room and book meeting rooms for events.</p><p>we already have example of web page, the mobile page would look the same:</p><p><em>Note: for sure in this case, it is easy to write a responsive page that can be use on mobile, but its a good introduction to understand how react native works.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*_uW7jwwtPucDbgKQ" /><figcaption>Screenshot from the final screen</figcaption></figure><h3>Setup project</h3><p>The code for this project is on <a href="https://github.com/fhenri/gmeet-react-native">https://github.com/fhenri/gmeet-react-native</a></p><p>You need to have usual <a href="https://nodejs.org/en">node</a> and <a href="https://www.npmjs.com/">npm</a> installed on your machine. We will use <a href="https://expo.dev/">expo</a> to develop our app.</p><p>We will create the project with following command</p><pre>npx create-expo-app@latest -t</pre><p>-t means we want to use a template, we select the typescript template and just proceed with the rest of questions</p><pre>Need to install the following packages:<br>create-expo-app@3.0.0<br>Ok to proceed? (y) y<br><br>✔ Choose a template: › Blank (TypeScript)<br>✔ What is your app named? … gmeet-native<br>✔ Downloaded and extracted project files.<br>&gt; npm install<br><br><br>.....<br><br>✅ Your project is ready!<br><br>To run your project, navigate to the directory and run one of the following npm commands.<br><br>- cd gmeet-native<br>- npm run android<br>- npm run ios<br>- npm run web<br><br></pre><p>You can follow the instructions to run it with an iOS or Android emulator.</p><p>Those must be installed:</p><ul><li>For iOS, you must install and run latest version of <a href="https://developer.apple.com/xcode/">xcode</a>.</li><li>For Android, you need to download <a href="https://developer.android.com/studio?hl=fr">Android Studio</a>.</li></ul><h4>iOS Simulator</h4><p>You need to make sure <a href="https://developer.apple.com/xcode/">xcode</a> is installed on your platform. You can install simulators from xcode, go to <em>Window / Devices and Simulators</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJ0PMYZ7jaNRkwgmQ7kRFA.png" /></figure><p>You can add simulators if you dont have any for the device of your choice and a specific iOS version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_K9sUFazwSESUuAvfzHUA.png" /></figure><p>When you</p><h4>Android Simulator</h4><p>You need to make sure <a href="https://developer.android.com/studio?hl=fr">Android Studio</a> is installed on your platform. You can install simulators from the Android Studio main screen, go to <em>More Actions / Virtual Device Manager</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFY1QHdLFIlJhh_GQiiPug.png" /></figure><p>You will get the list of all availabled devices currently installed and available</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4i0AH6YvtXt4hcYSLfPqug.png" /></figure><p>You can install new ones</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-x0wRV0hIMv3YST0p2D0TQ.png" /></figure><p>In the following we will work on iPhone layout and will run our app from</p><pre>npm run ios<br><br>Starting project at /Users/fhenri/project/gmeet/gmeet-react-native<br>Starting Metro Bundler<br>› Opening exp://192.168.100.129:8081 on iPhone 15<br>▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄<br>█ ▄▄▄▄▄ █ ██▀▀█▄▄██ ▄▄▄▄▄ █<br>█ █   █ █  ▀█ ▀█ ▄█ █   █ █<br>█ █▄▄▄█ █▀  █▄ ▀▄██ █▄▄▄█ █<br>█▄▄▄▄▄▄▄█▄█ ▀▄█ ▀ █▄▄▄▄▄▄▄█<br>█  ██▄▄▄███▄█▄▀▄▀▄██ ▀▄▄ ▄█<br>█  ▄▄█ ▄█  ▄█▀▄█ ▀▀ █▄  ▀██<br>█▀▄█▄▄ ▄▀██▀▄ █▄▀▄▀▄▀▀▄ ▀██<br>███ ▄██▄▄█▀  ▄█▀▄▄▄█▄▀ ▀███<br>█▄▄▄█▄▄▄▄ ██▀▀█▄▄ ▄▄▄ ▀ ▄▄█<br>█ ▄▄▄▄▄ █▀██ █▄█▀ █▄█ ▀▀▀▀█<br>█ █   █ █▄ █ ▀█▄█▄▄ ▄▄▀ ▀▀█<br>█ █▄▄▄█ █▀ █ ███▄██▄▀█▀▀ ██<br>█▄▄▄▄▄▄▄█▄▄████▄████▄▄▄▄▄▄█<br><br>› Metro waiting on exp://192.168.100.129:8081<br>› Scan the QR code above with Expo Go (Android) or the Camera app (iOS)<br><br>› Using Expo Go<br>› Press s │ switch to development build<br><br>› Press a │ open Android<br>› Press i │ open iOS simulator<br>› Press w │ open web<br><br>› Press j │ open debugger<br>› Press r │ reload app<br>› Press m │ toggle menu<br>› shift+m │ more tools<br>› Press o │ open project code in your editor<br><br>› Press ? │ show all commands<br><br>Logs for your project will appear below. Press Ctrl+C to exit.</pre><p>The default simulator will open. If you wish to change the iphone version, you can do shift + i and it will open the screen with all simulators installed</p><pre>? Select a simulator ›<br>❯   iPhone 15 (17.5)<br>    iPhone 15 Plus (17.5)<br>    iPhone 15 Pro (17.5)<br>    iPhone 15 Pro Max (17.5)<br>    iPad (10th generation) (17.5)<br>    iPad mini (6th generation) (17.5)<br>    iPad Air 11-inch (M2) (17.5)<br>    iPad Air 13-inch (M2) (17.5)<br>    iPad Pro 11-inch (M4) (17.5)<br>    iPad Pro 13-inch (M4) (17.5)<br>  ↓ iPhone SE (3rd generation) (17.5)</pre><h3>React Native Code</h3><p>The following code has been added by default to the app</p><pre>import { StatusBar } from &#39;expo-status-bar&#39;;<br>import { StyleSheet, Text, View } from &#39;react-native&#39;;<br><br>export default function App() {<br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;Text&gt;Open up App.tsx to start working on your app!&lt;/Text&gt;<br>      &lt;StatusBar style=&quot;auto&quot; /&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;#fff&#39;,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>  },<br>});</pre><p>View is like an html div that is a container where you will add your native elements and you can style. Style are <em>similar</em> (but not exactly) like css.</p><p>Text will allow to add text element on screen, that is the most basic way to push information to the user, but required, if you put text outside the Text element you’ll get error.</p><p>Let’s add some welcome text on top of the screen</p><pre>export default function App() {<br>  return (<br>  &lt;View style={styles.container}&gt;<br>    &lt;View style={styles.header}&gt;<br>      &lt;Text style={styles.headerText}&gt;Create Meeting Invite&lt;/Text&gt;<br>    &lt;/View&gt;<br>  &lt;/View&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;#fff&#39;,<br>  },<br>  header: {<br>    flexDirection: &quot;row&quot;,<br>    alignItems: &quot;center&quot;,<br>    justifyContent: &quot;space-between&quot;,<br>    padding: 20,<br>    borderBottomWidth: 1,<br>    borderBottomColor: &quot;#dee2e6&quot;,<br>  },<br>  headerText: {<br>    fontSize: 20,<br>    fontWeight: &quot;600&quot;,<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7YZmyBPqMy1suh-3uuoEw.png" /></figure><p>Quickly, we can see that we have an issue and the text is misplaced due to the iphone elements. React Native has a <a href="https://reactnative.dev/docs/safeareaview">SafeAreaView</a> component to fix that.</p><blockquote>The purpose of SafeAreaView is to render content within the safe area boundaries of a device. It is currently only applicable to iOS devices with iOS version 11 or later.</blockquote><p>We change the outer View with a SafeAreaView and it fixes the issue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpiP7OW5n-URwWyp9DXzWg.png" /></figure><p>Lets add an TextInput as the name implies, this will add an input box for user to enter any text. We will add the box for the meeting title and similar to react, we need to have a state for the title value.</p><pre>  const [title, setTitle] = useState(&quot;&quot;);<br><br>      &lt;View style={styles.formContainer}&gt;<br>        &lt;View&gt;<br>          &lt;TextInput<br>            style={styles.input}<br>            placeholder=&quot;Meeting Title&quot;<br>            value={title}<br>            onChangeText={(text) =&gt; {<br>              setTitle(text);<br>            }}<br>          /&gt;<br>        &lt;/View&gt;<br>      &lt;/View&gt;<br><br>const styles = StyleSheet.create({<br>  formContainer: {<br>    padding: 20,<br>    gap: 15,<br>  },<br>  input: {<br>    height: 40,<br>    borderColor: &quot;gray&quot;,<br>    borderWidth: 1,<br>    paddingHorizontal: 10,<br>    borderRadius: 4,<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRXw6qAtM_O7NRsaRBcGfw.png" /></figure><p>Next in our form, we need user to select the date and time of the meeting. For this, we need a dedicated component and searching the web for a nice native date-picker, our choice will be to use the <a href="https://www.npmjs.com/package/@react-native-community/datetimepicker"><em>react-native-community/datetimepicker</em></a><em>.</em></p><pre>npm install @react-native-community/datetimepicker --save</pre><p>Now we can add the date picker in our UI. We know that when user will change the date we usually have to check for available room on this date so we need to take into account in our handler</p><pre>import DateTimePicker from &quot;@react-native-community/datetimepicker&quot;;<br><br>...<br>export default function App() {<br>  const [title, setTitle] = useState(&quot;&quot;);<br>  const [meetingDate, setMeetingDate] = useState(new Date());<br><br>  const checkAvailableRoom = () =&gt; {<br>    return;<br>  };<br><br>  // Time/Date change handlers<br>  const onChangeDate = (selectedDate?: Date) =&gt; {<br>    if (selectedDate) {<br>      setMeetingDate(selectedDate);<br>      checkAvailableRoom();<br>    }<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>      .....<br><br>        &lt;View style={styles.row}&gt;<br>          &lt;Text style={styles.label}&gt;Meeting Date&lt;/Text&gt;<br>          &lt;DateTimePicker<br>            style={styles.flex1}<br>            testID=&quot;datePicker&quot;<br>            minimumDate={new Date()}<br>            value={meetingDate}<br>            mode=&quot;date&quot;<br>            onChange={(_, date) =&gt; onChangeDate(date)}<br>          /&gt;<br>        &lt;/View&gt;<br>      &lt;/View&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  ....<br>  flex1: {<br>    flex: 1,<br>  },<br>  row: {<br>    flexDirection: &quot;row&quot;,<br>    alignItems: &quot;center&quot;,<br>    gap: 10,<br>  },<br>  label: {<br>    fontSize: 16,<br>    minWidth: 60,<br>  },<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edutFxZYPmCH4wpb8WHhsQ.png" /></figure><p><em>Note: You need to restart after you installed new packages. If the app does not refresh correctly on your change, type </em><em>r to reload the app.</em></p><p>In same vein we can add 2 handlers for time, will be same but we’ll use mode=&quot;time&quot; instead of date. we can add an extra div (oh View ) so the 2 pickers will be on same row</p><pre>            &lt;View style={styles.timeContainer}&gt;<br>              &lt;View style={styles.timeGroup}&gt;<br>                &lt;Text style={styles.label}&gt;From&lt;/Text&gt;<br>                &lt;DateTimePicker<br>                  style={styles.flex1}<br>                  testID=&quot;fromTimePicker&quot;<br>                  value={timeFrom}<br>                  mode=&quot;time&quot;<br>                  onChange={(_, time) =&gt; onChangeFromTime(time)}<br>                /&gt;<br>              &lt;/View&gt;<br><br>              &lt;View style={styles.timeGroup}&gt;<br>                &lt;Text style={[styles.label, styles.textCenter]}&gt;To&lt;/Text&gt;<br>                &lt;DateTimePicker<br>                  style={styles.flex1}<br>                  value={timeTo}<br>                  mode=&quot;time&quot;<br>                  onChange={(_, time) =&gt; onChangeToTime(time)}<br>                /&gt;<br>              &lt;/View&gt;<br>            &lt;/View&gt;</pre><p>Note that we have style={[styles.label, styles.text center]} this is the way to add multiple styles on same element, they must be added within an array of style.</p><p>For description, we just define a TextInput with <strong>multiline</strong> properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qfa_L4gNBzF0TlCYvRU9bg.png" /></figure><pre>  const [timeFrom, setTimeFrom] = useState(new Date());<br>  const [timeTo, setTimeTo] = useState(new Date());<br>  const [description, setDescription] = useState(&quot;&quot;);<br>  <br>  ...<br>  const onChangeFromTime = (selectedTime?: Date) =&gt; {<br>    if (selectedTime) {<br>      setTimeFrom(selectedTime);<br>      checkAvailableRoom();<br>    }<br>  };<br><br>  const onChangeToTime = (selectedTime?: Date) =&gt; {<br>    if (selectedTime) {<br>      setTimeTo(selectedTime);<br>      checkAvailableRoom();<br>    }<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>    ...<br>        &lt;View style={styles.timeContainer}&gt;<br>          &lt;View style={styles.timeGroup}&gt;<br>            &lt;Text style={styles.label}&gt;From&lt;/Text&gt;<br>            &lt;DateTimePicker<br>              style={styles.flex1}<br>              testID=&quot;fromTimePicker&quot;<br>              value={timeFrom}<br>              mode=&quot;time&quot;<br>              onChange={(_, time) =&gt; onChangeFromTime(time)}<br>            /&gt;<br>          &lt;/View&gt;<br><br>          &lt;View style={styles.timeGroup}&gt;<br>            &lt;Text style={[styles.label, styles.textCenter]}&gt;To&lt;/Text&gt;<br>            &lt;DateTimePicker<br>              style={styles.flex1}<br>              value={timeTo}<br>              mode=&quot;time&quot;<br>              onChange={(_, time) =&gt; onChangeToTime(time)}<br>            /&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br><br>        &lt;TextInput<br>          style={[styles.input, styles.textArea]}<br>          placeholder=&quot;Description&quot;<br>          value={description}<br>          onChangeText={setDescription}<br>          multiline<br>          numberOfLines={4}<br>        /&gt;<br>      &lt;/View&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  ...<br>  timeContainer: {<br>    flexDirection: &quot;row&quot;,<br>    justifyContent: &quot;space-between&quot;,<br>    gap: 20,<br>  },<br>  timeGroup: {<br>    flexDirection: &quot;row&quot;,<br>    alignItems: &quot;center&quot;,<br>    flex: 1,<br>    gap: 10,<br>  },<br>  textCenter: {<br>    textAlign: &quot;center&quot;,<br>  },<br>  textArea: {<br>    height: 120,<br>    textAlignVertical: &quot;top&quot;,<br>    paddingTop: 10,<br>  },<br>});<br><br></pre><h4>Modal to manage the participants</h4><p>We need to manage the list of participants to the meeting. We could use the <a href="https://reactnative.dev/docs/flatlist">flatlist component</a> or a <a href="https://reactnative.dev/docs/scrollview">scrollview component</a>, the issue we would end up is that if our form is long, we would need to implement a scroll for our form, and then it is not possible to have scrollview and/or flatlist within an existing scrollview, you need to separate the content.</p><p>For our case, we can mitigate that by having the user adding the participants from the main form and have a <a href="https://reactnative.dev/docs/modal">modal component</a> to display and manage all those participants. We need the following code to create a modal. It takes a list of participants which are just Text, we need the following component to be added</p><ul><li>ScrollView the usual touch when you use your phone, you scroll</li><li>Pressable <a href="https://reactnative.dev/docs/pressable">component</a> which detect when screen are touched and interact with the screen.</li></ul><p>we can install the lucide library which provides nice icon to work with</p><pre>npm install lucide-react-native</pre><pre>import { Modal, Pressable, ScrollView } from &quot;react-native&quot;;<br>import { Trash, X } from &quot;lucide-react-native&quot;;<br><br>const ParticipantModal = ({<br>  visible,<br>  onClose,<br>  participants,<br>  onRemoveParticipant,<br>}: {<br>  visible: boolean;<br>  onClose: () =&gt; void;<br>  participants: string[];<br>  onRemoveParticipant: (email: string) =&gt; void;<br>}) =&gt; (<br>  &lt;Modal<br>    animationType=&quot;slide&quot;<br>    transparent={true}<br>    visible={visible}<br>    onRequestClose={onClose}<br>  &gt;<br>    &lt;View style={modalStyles.modalOverlay}&gt;<br>      &lt;View style={modalStyles.modalView}&gt;<br>        &lt;View style={modalStyles.modalHeader}&gt;<br>          &lt;Text style={modalStyles.modalTitle}&gt;Participants&lt;/Text&gt;<br>          &lt;Pressable onPress={onClose} style={styles.iconButton}&gt;<br>            &lt;X size={24} color=&quot;grey&quot; /&gt;<br>          &lt;/Pressable&gt;<br>        &lt;/View&gt;<br><br>        &lt;ScrollView&gt;<br>          {participants.length === 0 ? (<br>            &lt;Text style={modalStyles.noParticipantsText}&gt;<br>              No participants added yet<br>            &lt;/Text&gt;<br>          ) : (<br>            participants.map((participant, index) =&gt; (<br>              &lt;View key={index} style={modalStyles.modalParticipantItem}&gt;<br>                &lt;Text style={modalStyles.modalParticipantEmail}&gt;{participant}&lt;/Text&gt;<br>                &lt;Pressable<br>                  onPress={() =&gt; onRemoveParticipant(participant)}<br>                  style={styles.iconButton}<br>                &gt;<br>                  &lt;Trash size={20} color=&quot;grey&quot; /&gt;<br>                &lt;/Pressable&gt;<br>              &lt;/View&gt;<br>            ))<br>          )}<br>        &lt;/ScrollView&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  &lt;/Modal&gt;<br>);<br><br>const modalStyles = StyleSheet.create({<br>  modalOverlay: {<br>    flex: 1,<br>    backgroundColor: &quot;rgba(0, 0, 0, 0.5)&quot;,<br>    justifyContent: &quot;flex-end&quot;,<br>  },<br>  modalView: {<br>    backgroundColor: &quot;white&quot;,<br>    borderTopLeftRadius: 20,<br>    borderTopRightRadius: 20,<br>    padding: 20,<br>    maxHeight: &quot;80%&quot;,<br>  },<br>  modalHeader: {<br>    flexDirection: &quot;row&quot;,<br>    justifyContent: &quot;space-between&quot;,<br>    alignItems: &quot;center&quot;,<br>    marginBottom: 20,<br>  },<br>  modalTitle: {<br>    fontSize: 20,<br>    fontWeight: &quot;600&quot;,<br>  },<br>  modalParticipantItem: {<br>    flexDirection: &quot;row&quot;,<br>    justifyContent: &quot;space-between&quot;,<br>    alignItems: &quot;center&quot;,<br>    paddingVertical: 12,<br>    paddingHorizontal: 5,<br>    borderBottomWidth: 1,<br>    borderBottomColor: &quot;#E5E5E5&quot;,<br>  },<br>  modalParticipantEmail: {<br>    fontSize: 16,<br>    flex: 1,<br>  },<br>  noParticipantsText: {<br>    textAlign: &quot;center&quot;,<br>    color: &quot;#666&quot;,<br>    marginTop: 20,<br>    fontSize: 16,<br>  },<br>});</pre><p>We need to define an input box where user name will be entered and a user button to open the modal, as well as some handler to add/remove participants.</p><pre>import { Users } from &quot;lucide-react-native&quot;;<br><br>export default function App() {<br>  const [modalVisible, setModalVisible] = useState(false);<br>  const [participants, setParticipants] = useState&lt;string[]&gt;([]);<br>  const [newParticipant, setNewParticipant] = useState(&quot;&quot;);<br>  ...<br><br>  const handleAddParticipant = () =&gt; {<br>    if (newParticipant.trim()) {<br>      const updatedParticipants = [...participants, newParticipant.trim()];<br>      setParticipants(updatedParticipants);<br>      setNewParticipant(&quot;&quot;);<br>      checkAvailableRoom();<br>    }<br>  };<br><br>  const handleRemoveParticipant = (email: string) =&gt; {<br>    const updatedParticipants = participants.filter((p) =&gt; p !== email);<br>    setParticipants(updatedParticipants);<br>    checkAvailableRoom();<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>    ...<br><br>      &lt;View style={styles.participantsContainer}&gt;<br>        &lt;Text style={styles.participantLabel}&gt;Participants&lt;/Text&gt;<br>        &lt;View style={styles.row}&gt;<br>          &lt;TextInput<br>            style={[styles.input, styles.flex1]}<br>            placeholder=&quot;Add Participant Email&quot;<br>            value={newParticipant}<br>            onChangeText={setNewParticipant}<br>            onSubmitEditing={handleAddParticipant}<br>            returnKeyType=&quot;done&quot;<br>            keyboardType=&quot;email-address&quot;<br>            autoCapitalize=&quot;none&quot;<br>          /&gt;<br>          &lt;Pressable<br>            style={styles.viewParticipantsButton}<br>            onPress={() =&gt; setModalVisible(true)}<br>          &gt;<br>            &lt;Users size={20} color=&quot;black&quot; /&gt;<br>            &lt;Text style={styles.buttonText}&gt;View ({participants.length})&lt;/Text&gt;<br>          &lt;/Pressable&gt;<br>        &lt;/View&gt;<br>      &lt;/View&gt;<br><br>      &lt;ParticipantModal<br>        visible={modalVisible}<br>        onClose={() =&gt; setModalVisible(false)}<br>        participants={participants}<br>        onRemoveParticipant={handleRemoveParticipant}<br>      /&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  ...<br>  participantsContainer: {<br>    gap: 8,<br>  },<br>  participantLabel: {<br>    fontSize: 16,<br>    fontWeight: &quot;500&quot;,<br>    color: &quot;#333&quot;,<br>  },<br>  viewParticipantsButton: {<br>    flexDirection: &quot;row&quot;,<br>    alignItems: &quot;center&quot;,<br>    padding: 10,<br>    backgroundColor: &quot;#e5e7eb&quot;,<br>    borderRadius: 8,<br>    gap: 5,<br>  },<br>  buttonText: {<br>    fontWeight: &quot;500&quot;,<br>  },<br>});<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApkqLYhN59gGeWi590_qLA.png" /></figure><h3>Interact with our API endpoint</h3><p>You need to have the <a href="https://github.com/fhenri/booking-room">booking-room API</a> running locally so we can fetch data from server. As simple Javascript/React application we can fetch data from our server (you can use axios or other lib but for now we’ll use simple fetch)</p><p>so when we have all information for the meeting, we need to propose the list of available room we can get that from API</p><pre>  const [rooms, setRooms] = useState&lt;RoomElement[]&gt;([]);<br><br>  const checkAvailableRoom = async (capacity: number) =&gt; {<br>    const params = new URLSearchParams({<br>      capacity: capacity.toString(),<br>      date: format(meetingDate, &quot;yyyy-MM-dd&quot;),<br>      timeFrom: format(timeFrom, &quot;HH:mm&quot;),<br>      timeTo: format(timeTo, &quot;HH:mm&quot;),<br>    });<br><br>    try {<br>      const response = await fetch(<br>        `http://localhost:3000/api/schedule?${params}`<br>      );<br>      const data = await response.json();<br>      setRooms(<br>        data.rooms.map((room: Room) =&gt; ({<br>          label: room.name,<br>          value: room.id,<br>        }))<br>      );<br>    } catch (error) {<br>      Alert.alert(&quot;Error&quot;, &quot;Failed to fetch available rooms&quot;);<br>    }<br>  };</pre><p>We need to define some type for Room</p><pre>type Room = {<br>  id: string;<br>  name: string;<br>  capacity: number;<br>};<br><br>type RoomElement = {<br>  label: string;<br>  value: string;<br>};</pre><p>We need to update our function call to the checkAvailableRoom method so we pass the number of participants, this is specially usefull when we handle add/remove participants</p><pre>  const handleAddParticipant = () =&gt; {<br>    if (newParticipant.trim()) {<br>      const updatedParticipants = [...participants, newParticipant.trim()];<br>      setParticipants(updatedParticipants);<br>      setNewParticipant(&quot;&quot;);<br>      checkAvailableRoom(updatedParticipants.length);<br>    }<br>  };<br><br>  const handleRemoveParticipant = (email: string) =&gt; {<br>    const updatedParticipants = participants.filter((p) =&gt; p !== email);<br>    setParticipants(updatedParticipants);<br>    checkAvailableRoom(updatedParticipants.length);<br>  };</pre><p>For the date/time change we can just pass the participants state.</p><p>Now we have the list of available rooms, we need to let the user select the room he would like.</p><p>We would need to add a <a href="https://www.npmjs.com/package/@react-native-picker/picker">picker component</a> and date-fns to deal with date</p><pre>npm install @react-native-picker/picker date-fns</pre><pre>import { Picker } from &quot;@react-native-picker/picker&quot;;<br>import { format } from &quot;date-fns&quot;;<br><br>export default function App() {<br>  ...<br>  const [selectedRoom, setSelectedRoom] = useState(&quot;&quot;);<br><br>      ...<br>      &lt;View&gt;<br>        &lt;Picker<br>          style={styles.picker}<br>          selectedValue={selectedRoom}<br>          onValueChange={(itemValue) =&gt; {<br>            setSelectedRoom(itemValue);<br>          }}<br>        &gt;<br>          &lt;Picker.Item label=&quot;Select Meeting Room&quot; value=&quot;&quot; /&gt;<br>          {rooms.map((room) =&gt; (<br>            &lt;Picker.Item<br>              key={room.value}<br>              label={room.label}<br>              value={room.value}<br>            /&gt;<br>          ))}<br>        &lt;/Picker&gt;<br>      &lt;/View&gt;<br>      ...<br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  ...<br>  picker: {<br>    marginVertical: 5,<br>  },<br>});</pre><p>And we get a picker element at the bottom of the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG1vCTsTN3X4TAOzXz7nAA.png" /></figure><p>We miss the final part : a submit button that will submit the form and create an event for this meeting room.</p><pre>export default function App() {<br><br>  const [isSubmitting, setIsSubmitting] = useState(false);<br>  ...<br><br>  ...<br>  const handleSubmit = async () =&gt; {<br>    if (isSubmitting) return;<br>    setIsSubmitting(true);<br><br>    try {<br>      const response = await fetch(&quot;http://localhost:3000/api/schedule&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify({<br>          title,<br>          date: format(meetingDate, &quot;yyyy-MM-dd&quot;),<br>          timeFrom: format(timeFrom, &quot;HH:mm&quot;),<br>          timeTo: format(timeTo, &quot;HH:mm&quot;),<br>          description,<br>          guests: participants,<br>          roomId: selectedRoom,<br>        }),<br>      });<br><br>      await response.json();<br>      Alert.alert(&quot;Success&quot;, &quot;Meeting has been scheduled successfully&quot;);<br>    } catch (error) {<br>      Alert.alert(&quot;Error&quot;, &quot;Failed to schedule meeting. Please try again.&quot;);<br>    } finally {<br>      setIsSubmitting(false);<br>    }<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>    ...<br><br>        &lt;Pressable<br>          style={[styles.submitButton, isSubmitting &amp;&amp; styles.disabled]}<br>          onPress={handleSubmit}<br>          disabled={isSubmitting}<br>        &gt;<br>          &lt;Text style={styles.submitButtonText}&gt;Submit&lt;/Text&gt;<br>        &lt;/Pressable&gt;<br>      &lt;/View&gt;<br><br>    ... <br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  ...<br>  submitButton: {<br>    backgroundColor: &quot;#1C1917&quot;,<br>    paddingVertical: 12,<br>    alignItems: &quot;center&quot;,<br>    borderRadius: 8,<br>    marginTop: 20,<br>  },<br>  submitButtonText: {<br>    color: &quot;#FAFAF9&quot;,<br>    fontWeight: &quot;bold&quot;,<br>    fontSize: 16,<br>  },<br>  disabled: {<br>    opacity: 0.5,<br>  },<br>});</pre><p>And we have a one page form running natively as a mobile app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ud4qEtZSkUA29K0efD_rYA.png" /></figure><h3>Handle errors</h3><p>The final touch would be to handle errors and validate the form elements. We will create a new component to display error message</p><pre>import { AlertCircle } from &quot;lucide-react-native&quot;;<br><br>type FormErrors = {<br>  title?: string;<br>  meetingDate?: string;<br>  timeFrom?: string;<br>  timeTo?: string;<br>  participants?: string;<br>  selectedRoom?: string;<br>};<br><br>const ErrorMessage = ({ message }: { message?: string }) =&gt; {<br>  if (!message) return null;<br>  return (<br>    &lt;View style={styles.errorContainer}&gt;<br>      &lt;AlertCircle size={16} color=&quot;#dc2626&quot; /&gt;<br>      &lt;Text style={styles.errorText}&gt;{message}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>const errorStyles = StyleSheet.create({<br>  errorContainer: {<br>    flexDirection: &quot;row&quot;,<br>    alignItems: &quot;center&quot;,<br>    marginTop: 4,<br>    gap: 4,<br>  },<br>  errorText: {<br>    color: &quot;#dc2626&quot;,<br>    fontSize: 12,<br>  },<br>});<br></pre><p>Lets add a state to maintain the list of errors</p><pre><br>export default function App() {<br>  ...<br>  const [rooms, setRooms] = useState&lt;RoomElement[]&gt;([]);<br><br>  const onChangeToTime = (selectedTime?: Date) =&gt; {<br>    if (selectedTime) {<br>      setTimeTo(selectedTime);<br>      setErrors((prev) =&gt; ({<br>        ...prev,<br>        timeTo: selectedTime &lt; timeFrom ? &quot;End time cannot be before start time&quot; : undefined,<br>      }));<br>      checkAvailableRoom(participants.length);<br>    }<br>  };<br><br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br>    ....<br><br>          &lt;View style={styles.timeGroup}&gt;<br>            &lt;Text style={[styles.label, styles.textCenter]}&gt;To&lt;/Text&gt;<br>            &lt;DateTimePicker<br>              style={styles.flex1}<br>              value={timeTo}<br>              mode=&quot;time&quot;<br>              onChange={(_, time) =&gt; onChangeToTime(time)}<br>            /&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br>        &lt;ErrorMessage message={errors.timeTo} /&gt;<br><br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9YCnuxbrc7YX0hqH0iv8A.png" /></figure><p>We can also validate all fields when we click on submit button</p><pre><br>export default function App() {<br>  ...<br><br>  const validateForm = (): boolean =&gt; {<br>    const newErrors: FormErrors = {};<br><br>    if (!title?.trim()) newErrors.title = &quot;Title is required&quot;;<br>    if (isBefore(meetingDate, startOfDay(new Date()))) {<br>      newErrors.meetingDate = &quot;Meeting date cannot be in the past&quot;;<br>    }<br>    if (isBefore(timeTo, timeFrom)) {<br>      newErrors.timeTo = &quot;End time cannot be before start time&quot;;<br>    }<br>    if (participants.length === 0) {<br>      newErrors.participants = &quot;At least one participant is required&quot;;<br>    }<br>    if (!selectedRoom) newErrors.selectedRoom = &quot;Please select a meeting room&quot;;<br><br>    setErrors(newErrors);<br>    return Object.keys(newErrors).length === 0;<br>  };<br><br>  const handleSubmit = async () =&gt; {<br>    if (isSubmitting) return;<br>    setIsSubmitting(true);<br><br>    if (!validateForm()) {<br>      setIsSubmitting(false);<br>      return;<br>    }<br>    ...<br>  }<br><br>  //-------------------------------------------------------<br>  // Add the error component next to all form fields<br>  // adding example for the title field but need to be done<br>  // for other required field - refer to code.<br>  //-------------------------------------------------------<br>  return (<br>    &lt;SafeAreaView style={styles.container}&gt;<br><br>            &lt;View&gt;<br>              &lt;TextInput<br>                style={[styles.input, errors.title &amp;&amp; styles.inputError]}<br>                placeholder=&quot;Meeting Title&quot;<br>                value={title}<br>                onChangeText={(text) =&gt; {<br>                  setTitle(text);<br>                  if (errors.title) {<br>                    setErrors((prev) =&gt; ({ ...prev, title: undefined }));<br>                  }<br>                }}<br>              /&gt;<br>              &lt;ErrorMessage message={errors.title} /&gt;<br>            &lt;/View&gt;<br><br>    &lt;/SafeAreaView&gt;<br>  );<br>}<br></pre><p>Congrats for reading till the end, thats a small introduction into the world of mobile and native apps using react-native.</p><p>I hope you learnt something out of your time reading the article, please leave your question if something you dont understand or is not clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea72b4963a23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conversation Telegram Bot with grammy deployed on Cloudflare]]></title>
            <link>https://javascript.plainenglish.io/conversation-telegram-bot-with-grammy-deployed-on-cloudflare-8f691515c365?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f691515c365</guid>
            <category><![CDATA[cloudflare-workers]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 09:09:25 GMT</pubDate>
            <atom:updated>2024-11-22T11:12:51.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Conversation Telegram Bot with grammY deployed on Cloudflare</h3><p>Development of a Telegram bot that can handle a conversation (we’ll use a <a href="https://grammy.dev/plugins/conversations">grammY plugin</a>) and fetch data from an API endpoint, all that deployed in a Cloudflare worker.</p><figure><img alt="bot conversation" src="https://cdn-images-1.medium.com/max/1024/0*3rkuMN_rnmZumT9m" /><figcaption>Photo by <a href="https://unsplash.com/@askkell?utm_source=medium&amp;utm_medium=referral">Andy Kelly</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The code for this article is on <a href="https://github.com/fhenri/telegram-meeting-bot">Github</a>.</p><p>Lets review what we want to achieve:</p><ul><li>The goal is to interact with a Telegram bot</li><li>User can ask the bot to create a meeting (we did deploy some meeting API with NextJS in <a href="https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-i-2393a80a70d0">previous article</a>)</li><li>The bot will ask a series of questions (meeting title, date …)</li><li>The bot will fetch available rooms based on the meeting criteria (date/time and number of participants)</li><li>The bot can create a meeting in a particular room</li><li>We will deply the bot on <a href="https://grammy.dev/hosting/cloudflare-workers-nodejs">Cloudflare worker</a>.</li></ul><h3>Creating the Telegram bot</h3><p>There are a numbers of <a href="https://core.telegram.org/bots/tutorial">article</a> to explain how to create a bot but it is rather simple.</p><p>A <strong>bot token</strong> is a string that authenticates your bot (not your account) on the bot API. Each bot has a unique token which can also be revoked at any time via <a href="https://t.me/botfather">@BotFather</a>.</p><p>Obtaining a token is as simple as contacting <a href="https://t.me/botfather">@BotFather</a>, issuing the /newbot command and following the steps until you&#39;re given a new token. You can find a step-by-step guide <a href="https://core.telegram.org/bots/features#creating-a-new-bot">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*BPrHn5LtjcWAYhdkUOeGTw.png" /></figure><blockquote>The most difficult will be to find an available username for your bot!</blockquote><p>At the end of the process, you will be given a token, it will look something like this:</p><pre>1234567890:AABB33DD55FFGGHH11JJKKLLMMNN00PPQQX</pre><p>Note that this token has to be saved in secure place, treat it like a password and <strong>don’t share it with anyone</strong>.</p><p>Since we do configure the bot, you can add the <strong>command</strong> we will be using. You can configure bot settings from <a href="https://t.me/botfather">@BotFather</a> and calling /mybots select your bot, then <strong>Edit bot</strong> and <strong>Edit Commands. </strong>You can provide the command as explained so for us</p><pre>create - create a meeting</pre><p>and now if you go to the chat window of your new bot, you will see the menu button and the available command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*zEaYIBj3almksu-Wvhw3gQ.png" /></figure><h3>Bot development</h3><p>If you navigate to the <a href="https://core.telegram.org/bots/samples">Telegram documentation</a>, you will multiple Bot API libraries. As usual, you should review based on your preferences, support, history … In our case we will use the <a href="https://github.com/grammyjs/grammY"><strong>grammY </strong>Telegram Bot Framework</a>.</p><p>It is a well developed library, it has <a href="https://grammy.dev/plugins/">plugin framework</a> (and <a href="https://grammy.dev/plugins/conversations">conversations</a> are supported) as well as an example to deploy on <a href="https://grammy.dev/hosting/cloudflare-workers-nodejs">Cloudflare workers</a>.</p><h4>Creating the project</h4><pre>npm create cloudflare@latest -- telegram-bot/</pre><p>This creates a new project with a Cloudflare template in the telegram-bot folder. You might have to install/update the Cloudflare lib</p><pre>Need to install the following packages:<br>create-cloudflare@2.32.2<br>Ok to proceed? (y) y<br><br><br>&gt; npx<br>&gt; create-cloudflare telegram-bot/</pre><p>And then it will prompt a few questions</p><pre>╭ Create an application with Cloudflare Step 1 of 3<br>│<br>├ In which directory do you want to create your application?<br>│ dir ./telegram-bot/<br>│<br>├ What would you like to start with?<br>│ category Hello World example<br>│<br>├ Which template would you like to use?<br>│ type Hello World Worker<br>│<br>├ Which language do you want to use?<br>│ lang TypeScript<br>│<br>├ Copying template files<br>│ files copied to project directory<br>│<br>├ Updating name in `package.json`<br>│ updated `package.json`<br>│<br>├ Installing dependencies<br>│ installed via `npm install`<br>│<br>╰ Application created<br><br>╭ Configuring your application for Cloudflare Step 2 of 3<br>│<br>├ Installing @cloudflare/workers-types<br>│ installed via npm<br>│<br>├ Adding latest types to `tsconfig.json`<br>│ added @cloudflare/workers-types/2023-07-01<br>│<br>├ Retrieving current workerd compatibility date<br>│ compatibility date 2024-11-12<br>│<br>├ Do you want to use git for version control?<br>│ yes git<br>│<br>├ Initializing git repo<br>│ initialized git<br>│<br>├ Committing new files<br>│ git commit<br>│<br>╰ Application configured<br><br>╭ Deploy with Cloudflare Step 3 of 3<br>│<br>├ Do you want to deploy your application?<br>│ no deploy via `npm run deploy`<br>│<br>╰ Done<br><br>────────────────────────────────────────────────────────────<br>🎉  SUCCESS  Application created successfully!</pre><p>You do not need to deploy for now, we will do that later in process.</p><p>We can configure our secret. Locally create the .dev.vars and add our secret (by default cloudflare has added .dev.vars into the .gitignore )</p><pre>1234567890:AABB33DD55FFGGHH11JJKKLLMMNN00PPQQX</pre><p>and for the worker we can run following</p><pre>npx wrangler secret put BOT_TOKEN</pre><p>and enter the token when prompted.</p><h4>Setting up grammY and Telegram bot</h4><p>we can install the required dependencies for grammY</p><pre>npm install grammy @grammyjs/storage-free @ponomarevlad/grammyjs-conversations date-fns</pre><p>we install grammyjs-conversations from @ponomarevlad due to following issue <a href="https://github.com/grammyjs/grammY/issues/372">https://github.com/grammyjs/grammY/issues/372</a> but it should be fixed in the core plugin anytime soon.</p><p>we also add date-fns library as we will work with dates, it makes it easier with date format.</p><p>You know need to download your bot info for grammY to work properly, you can get your bot info by calling Telegram Bot API with getMe method. Open this link in your web browser:</p><pre>https://api.telegram.org/bot&lt;BOT_TOKEN&gt;/getMe</pre><p>Replace &lt;BOT_TOKEN&gt; with your bot token. If successful, you will see a JSON response similar to this:</p><pre>{<br>    &quot;ok&quot;: true,<br>    &quot;result&quot;: {<br>        &quot;id&quot;: 1234567890,<br>        &quot;is_bot&quot;: true,<br>        &quot;first_name&quot;: &quot;&lt;bot name&gt;&quot;,<br>        &quot;username&quot;: &quot;&lt;bot username&gt;&quot;,<br>        &quot;can_join_groups&quot;: true,<br>        &quot;can_read_all_group_messages&quot;: false,<br>        &quot;supports_inline_queries&quot;: true,<br>        &quot;can_connect_to_business&quot;: false,<br>        &quot;has_main_web_app&quot;: false<br>    }<br>}</pre><p>Now, open wrangler.toml in the root of your project and add an environment variable BOT_INFO under [vars] section with the value from result object you get above like this:</p><pre>[vars]<br>BOT_INFO = &quot;&quot;&quot;{<br>    &quot;id&quot;: 1234567890,<br>    &quot;is_bot&quot;: true,<br>    &quot;first_name&quot;: &quot;&lt;bot name&gt;&quot;,<br>    &quot;username&quot;: &quot;&lt;bot username&gt;&quot;,<br>    &quot;can_join_groups&quot;: true,<br>    &quot;can_read_all_group_messages&quot;: false,<br>    &quot;supports_inline_queries&quot;: true,<br>    &quot;can_connect_to_business&quot;: false,<br>    &quot;has_main_web_app&quot;: false<br>}&quot;&quot;&quot;</pre><h4>Initial program and deploy</h4><p>With all this configuration, we can already develop the bot that will respond to the /create command</p><pre>import { Bot, Context, webhookCallback } from &quot;grammy&quot;;<br><br>export interface Env {<br>  BOT_INFO: string;<br>  BOT_TOKEN: string;<br>}<br><br>export default {<br>  async fetch(<br>    request: Request,<br>    env: Env,<br>    ctx: ExecutionContext,<br>  ): Promise&lt;Response&gt; {<br>    const bot = new Bot(env.BOT_TOKEN, { botInfo: JSON.parse(env.BOT_INFO) });<br><br>    // when user types /create it will be handled there<br>    bot.command(&quot;create&quot;, async (ctx: Context) =&gt; {<br>      await ctx.reply(&quot;We will go throug series of questions to create a meeting&quot;);<br>    });<br><br>    // Just added so we handle all messages from users just by echo the message<br>    bot.on(&#39;message&#39;, async (ctx) =&gt; {<br>     const message = ctx.msg.text;<br>     await ctx.reply(`I repeat your message: ${message}`);<br>    });<br><br>    return webhookCallback(bot, &quot;cloudflare-mod&quot;)(request);<br>  },<br>};</pre><p>and you’re ready to deploy</p><pre>npx wrangler deploy<br><br> ⛅️ wrangler 3.88.0<br>-------------------<br><br>Total Upload: 359.88 KiB / gzip: 73.90 KiB<br>Worker Startup Time: 20 ms<br>Your worker has access to the following bindings:<br>- Vars:<br>  - BOT_INFO: &quot;{<br> &quot;id&quot;: 8024401022,<br> &quot;is_bot&quot;: true,...&quot;<br>Uploaded &lt;bot name&gt; (8.00 sec)<br>Deployed &lt;bot name&gt; triggers (1.53 sec)<br>  https://&lt;bot name&gt;.&lt;your_subdomain&gt;.workers.dev<br>Current Version ID: 342f5819-20a2-4b3d-8c6c-b52ef0aa74c2</pre><p>There are 2 ways to handle a telegram bot, you can either launch your program and listen to the telegram chat (it is called long polling) or we can wait for telegram to update our program where there is an update in the chat (thats done with Webhook). grammY has nice <a href="https://grammy.dev/guide/deployment-types">documentation</a> about long polling vs webhooks, but in context of Cloudflare, we are doing Webhooks. The Webhook must be registered then in telegram, so telegram will know where to send the update when it gets one. You just need to hit</p><pre>https://api.telegram.org/bot&lt;BOT_TOKEN&gt;/setWebhook?url=https://&lt;bot name&gt;.&lt;your_subdomain&gt;.workers.dev</pre><p>If things are correct, you will receive</p><pre>{<br> &quot;ok&quot;: true,<br> &quot;result&quot;: true,<br> &quot;description&quot;: &quot;Webhook was set&quot;<br>}</pre><p>You can open a chat in Telegram with your bot. If you type a message, the bot will repeat your message and if you type /create it will prompt the message to start the conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*454oxktouauCz4x6eAoJHw.png" /></figure><h4>Setup the conversation</h4><p>By default, grammY suggests to use the Session plugin, and we’ll use the default storage. With typescript verbosity, the skeleton of our program will be</p><pre>import { Bot, Context, session, SessionFlavor, webhookCallback } from &#39;grammy&#39;;<br>import { type Conversation, type ConversationFlavor, conversations, createConversation } from &#39;@ponomarevlad/grammyjs-conversations&#39;;<br>import { freeStorage } from &#39;@grammyjs/storage-free&#39;;<br><br>interface SessionData {<br> message: string;<br>}<br><br>type MyContext = Context &amp; SessionFlavor&lt;SessionData&gt; &amp; ConversationFlavor;<br>type MyConversation = Conversation&lt;MyContext&gt;;<br><br><br>export interface Env {<br> BOT_INFO: string;<br> BOT_TOKEN: string;<br>}<br><br>export default {<br> async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise&lt;Response&gt; {<br>  const bot = new Bot&lt;MyContext&gt;(env.BOT_TOKEN, {<br>   botInfo: JSON.parse(env.BOT_INFO),<br>  });<br><br>  async function meeting(conversation: MyConversation, ctx: MyContext) {<br>      ...<br>  }<br><br>  bot.use(<br>   session({<br>    storage: freeStorage&lt;SessionData&gt;(bot.token),<br>    initial: () =&gt; ({ message: &#39;&#39; }),<br>   })<br>  );<br>  bot.use(conversations());<br><br>  bot.use(createConversation(meeting));<br>  bot.command(&#39;create&#39;, async (ctx) =&gt; {<br>   await ctx.conversation.enter(&#39;meeting&#39;);<br>  });<br><br>  bot.on(&#39;message&#39;, async (ctx) =&gt; {<br>   const message = ctx.msg.text;<br>   await ctx.reply(`do /create to create a new meeting`);<br>  });<br><br>  return webhookCallback(bot, &#39;cloudflare-mod&#39;)(request);</pre><p>First we will define the meeting method that is where the conversation will take place, the method will be registered just after.</p><p>As per <a href="https://grammy.dev/plugins/conversations#installing-and-entering-a-conversation">documentation</a>, we must use session plugin and we define our storage. Next we register the conversation method ( meeting ) in the conversation plugin middleware. Now the method is registered, we can invoke from any handler on any command/message so in our case on /create we will invoke the meeting conversation.</p><h4>Develop the conversation</h4><p>Now the skeleton is in place, we must integrate the conversation. The question the bot will ask will be in the form</p><pre>   await ctx.reply(&#39;Enter the Title for the Meeting [Meeting Title] ?&#39;);<br>   const meetingTitleCtx = await conversation.wait();<br><br>   await ctx.reply(&#39;Enter the Date of the Meeting [format DD/MM/YYYY] ?&#39;);<br>   const meetingDateCtx = await conversation.wait();<br><br>   await ctx.reply(&#39;Enter the Start Time of the Meeting [Meeting Sart] ?&#39;);<br>   const startTimeCtx = await conversation.wait();<br><br>   ...<br></pre><p>The meetingTitleCtx contains all context of what the user has replied including the username, date etc, for us we’ll be interested to get the text (ie what the user has entered as text to the question). meetingTitleCtx.message.text will contain this data and thats what we will be using</p><p>For the date, we ask user to respect a certain format so we’ll have to validate, it will be better to write its own function to read and parse the date (hence the date-fns library)</p><pre>async function getMeetingDate(conversation: MyConversation, ctx: MyContext): Promise&lt;Date&gt; {<br> let meetingDate: Date | null = null;<br><br> do {<br>  await ctx.reply(&#39;Enter the Meeting Date (format DD/MM/YYYY)&#39;);<br>  const meetingDateCtx = await conversation.wait();<br><br>  if (!meetingDateCtx || !meetingDateCtx.message) {<br>   await ctx.reply(&#39;Error: Invalid meeting date.&#39;);<br>   continue;<br>  }<br><br>  meetingDate = parse(meetingDateCtx.message.text!, &#39;dd/MM/yyyy&#39;, new Date());<br><br>  // Check if the parsed date is valid<br>  if (isNaN(meetingDate.getTime())) {<br>   await ctx.reply(&#39;Error: Invalid date format. Please use DD/MM/YYYY.&#39;);<br>   meetingDate = null;<br>   continue;<br>  }<br><br>  // Check if the date is in the past<br>  const today = await conversation.now();<br>  if (isAfter(today, meetingDate)) {   await ctx.reply(&#39;Error: Meeting date cannot be in the past.&#39;);<br>   meetingDate = null;<br>  }<br> } while (meetingDate === null);<br><br> return meetingDate!;<br>}</pre><p>we parse the text provided by user until it matches a date and the date is not in past. (note we’re using await conversation.now() to get the date, grammY offers <a href="https://grammy.dev/ref/conversations/conversationhandle#methods">convenient methods</a> for some use cases) and we do repeat the question until we get a valid date we can return.</p><p>we could do same for time but lets move on to more interesting thing</p><pre>   await ctx.reply(&#39;Enter the Title for the Meeting [Meeting Title] ?&#39;);<br>   const meetingTitleCtx = await conversation.wait();<br><br>   const meetingDate = await getMeetingDate(conversation, ctx);<br><br>   await ctx.reply(&#39;Enter Start Time (format HH:mm)&#39;);<br>   const startTimeCtx = await conversation.wait();<br><br>   await ctx.reply(&#39;Enter End Time (format HH:mm)&#39;);<br>   const endTimeCtx = await conversation.wait();<br><br>   await ctx.reply(&#39;Enter Participants (1 participant on each line)&#39;);<br>   const participantsCtx = await conversation.wait();<br>   const participantsList: string[] = participantsCtx.message?.text?.split(&#39;\n&#39;) || [ctx.from?.username || &#39;&#39;];<br>   const participantNb = participantsList.length || 1;</pre><p>We get the following information so far:</p><ul><li>meeting Title</li><li>meeting date</li><li>meeting start/end time (we’ll assume those are correct)</li><li>list of participants and number of participants (if it is not provided we’ll take the current user as participant so it will always be 1)</li></ul><p>Now we need to get the available room from our API.</p><p>Number 1 rule of the <a href="https://grammy.dev/plugins/conversations#three-golden-rules-of-conversations">conversations golden rule</a> is to wrap any code on external system with a conversation.external() so we’ll get something like this which will wrap the call of our API call</p><pre>   const roomList = await conversation.external(<br>    async () =&gt; await getMeetingRoom(<br>     conversation,<br>     ctx,<br>     participantNb.toString(),<br>     meetingDate.toISOString().split(&#39;T&#39;)[0],<br>     startTimeCtx.message?.text || &#39;&#39;,<br>     endTimeCtx.message?.text || &#39;&#39;<br>    )<br>   );</pre><p>and the getMeetingRoom will be the API call to our endpoint with the parameters:</p><pre>async function getMeetingRoom(<br> conversation: MyConversation,<br> ctx: MyContext,<br> participantNb: string,<br> meetingDate: string,<br> startTime: string,<br> endTime: string<br>) {<br> // call to get the list of available rooms<br> const params = new URLSearchParams({<br>  capacity: participantNb,<br>  date: meetingDate,<br>  timeFrom: startTime,<br>  timeTo: endTime,<br> });<br><br> const responseSchedule = await fetch(`https://booking-room.cloud06.io/api/schedule?${params}`);<br><br> if (responseSchedule.status !== 200) {<br>  await ctx.reply(`Error when getting available rooms: ${responseSchedule.statusText}`);<br>  return;<br> }<br><br> const data = (await responseSchedule.json()) as RoomElements;<br> return data;<br>}</pre><p>The bot will display all available rooms and ask the user to select one based on the list</p><pre>   const selectedRoomId = await getRoomForMeeting(<br>    conversation, ctx,<br>    roomList<br>   )</pre><p>and the getRoomForMeeting. It just loops through the list of rooms from the list, assign an index to each room; we also store a mapping of index and roomId so when user will send the room index number, we can map it to the real roomId back for our createMeeting API.</p><pre>async function getRoomForMeeting (<br> conversation: MyConversation,<br> ctx: MyContext,<br> roomList: RoomElements | undefined<br>): Promise&lt;string | undefined&gt; {<br><br> if (roomList &amp;&amp; roomList.rooms &amp;&amp; roomList.rooms.length &gt; 0) {<br>  let message = &#39;&lt;b&gt;Room Selection&lt;/b&gt;\n\n&#39;;<br>  message += &quot;&lt;pre&gt;&lt;code class=&#39;language-html&#39;&gt;\n&quot;;<br>  message += &#39;ID  | Room Name         | Capacity\n&#39;;<br>  message += &#39;----+-------------------+----------\n&#39;;<br>  roomList.rooms.forEach((room: Room, index: number) =&gt; {<br>   message += `${index + 1}  | ${room.name.padEnd(18)} | ${room.capacity}\n`;<br>  });<br>  message += &#39;&lt;/code&gt;&lt;/pre&gt;\n\n&#39;;<br>  message += &#39;Select a room by its ID number.&#39;;<br><br>  // Store mapping for later use<br>  const roomIdMap: { [key: number]: string } =<br>   roomList.rooms.reduce((acc, room, index) =&gt; {<br>    acc[index + 1] = room.id;<br>    return acc;<br>   }, {} as { [key: number]: string });<br><br>  await ctx.reply(message, { parse_mode: &#39;HTML&#39; });<br>  const roomSelectionCtx = await conversation.wait();<br>  const selectedRoom =<br>   parseInt(roomSelectionCtx?.message?.text || &#39;&#39;, 10);<br><br>  return roomIdMap[selectedRoom];<br> } else {<br>  return;<br> }<br><br>}</pre><p>It will render a table as below where user can provide the room index id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*mpp9skrT-8g83EHWVaSEZg.png" /></figure><p>Once the user will provide the room, we now have all elements to create a meeting. Again we need to wrap our API call inside conversation.external()</p><pre>   const bookingMessage = await conversation.external(<br>    async () =&gt; await bookMeetingRoom(<br>     conversation,<br>     ctx,<br>     meetingTitleCtx.message?.text,<br>     meetingDate.toISOString().split(&#39;T&#39;)[0],<br>     startTimeCtx.message?.text || &#39;&#39;,<br>     endTimeCtx.message?.text || &#39;&#39;,<br>     participantsList,<br>     selectedRoomId<br>    )<br>   );</pre><p>and the bookMeetingRoom will do the POST to our API</p><pre>async function bookMeetingRoom(<br> conversation: MyConversation,<br> ctx: MyContext,<br> meetingTitle: string | undefined,<br> meetingDate: string,<br> startTime: string,<br> endTime: string,<br> participantList: string[],<br> selectedRoomId: string | undefined<br>): Promise&lt;string&gt; {<br> const meetingData = {<br>  title: meetingTitle,<br>  date: meetingDate,<br>  timeFrom: startTime,<br>  timeTo: endTime,<br>  guests: participantList,<br>  roomId: selectedRoomId,<br> };<br><br> const responseMeeting = await fetch(&#39;https://booking-room.cloud06.io/api/schedule&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: {<br>   &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  },<br>  body: JSON.stringify(meetingData),<br> });<br><br> if (responseMeeting.status !== 200) {<br>  return `Error when creating event: ${responseMeeting.statusText}`;<br> }<br><br> const resultMeeting: EventMessage = await responseMeeting.json();<br> return resultMeeting.event.message;<br>}</pre><h4>Cancel during the form</h4><p>Since the form is a bit lenghty and you could make mistake, want to go back etc, we’ll add a /cancel command for user</p><pre>  bot.use(conversations());<br><br>  // Always exit any conversation upon /cancel<br>  bot.command(&quot;cancel&quot;, async (ctx) =&gt; {<br>   await ctx.conversation.exit();<br>   await ctx.reply(&quot;Leaving.&quot;);<br>  });<br><br>  bot.use(createConversation(meeting));<br>  bot.command(&#39;create&#39;, async (ctx) =&gt; {<br>   await ctx.conversation.enter(&#39;meeting&#39;);<br>  });<br><br>  bot.on(&#39;message&#39;, async (ctx) =&gt; {<br>   const message = ctx.msg.text;<br>   await ctx.reply(`do /create to create a new meeting`);<br>  });</pre><p>Note the order for the middleware. The /cancel command must be before the conversation so it will be call even inside the conversation process, it will take the current conversation from context and will exit the conversation, so user will be safe to start a new conversation with the bot.</p><p>If you want to unplug your bot, you dont have to stop the worker, you can delete the Webhook</p><pre>https://api.telegram.org/bot&lt;BOT_TOKEN&gt;/deleteWebhook<br><br>{<br> &quot;ok&quot;: true,<br> &quot;result&quot;: true,<br> &quot;description&quot;: &quot;Webhook was deleted&quot;<br>}</pre><p>and you can plug it back as simple as a request to /setWebhook endpoint.</p><p>And you’re done! congrats if you made it this far. If there’s something you have comments, don’t hesitate to shoot and ask any questions.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f691515c365" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/conversation-telegram-bot-with-grammy-deployed-on-cloudflare-8f691515c365">Conversation Telegram Bot with grammy deployed on Cloudflare</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create API Endpoint with Python Flask and Docker deployment]]></title>
            <link>https://medium.com/@frederic.henri/create-api-endpoint-with-python-flask-and-docker-deployment-a1d123d7fbcf?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d123d7fbcf</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 06:46:27 GMT</pubDate>
            <atom:updated>2024-11-19T06:46:27.218Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll discuss how we can create an API endpoint using <a href="https://flask.palletsprojects.com/en/stable/">Flask</a> for our <a href="https://medium.com/@frederic.henri/generate-pdf-invoice-from-html-using-python-and-jinja-08fb401a90e3">PDF Generator python script</a> and deploy the app on <a href="https://www.docker.com/">docker</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1wlUUpNDrh_SYszJ" /><figcaption>Photo by <a href="https://unsplash.com/@hdbernd?utm_source=medium&amp;utm_medium=referral">Bernd 📷 Dittrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Setting up Flask</h3><p>We will be using the existing <a href="https://medium.com/@frederic.henri/generate-pdf-invoice-from-html-using-python-and-jinja-08fb401a90e3">InvoicePDF script</a>, we had created a virtual environment so we need to make sure to install Flask within this environment</p><pre>$ source venv/bin/activate<br>venv $ pip install flask</pre><blockquote>Flask is a lightweight WSGI (Web Server Gateway Interface) web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications</blockquote><p>We will use Flask to respond to HTTP request, so for example, we can create the hello world endpoint, lets create app.py file:</p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hey Invoice Generation App!&#39;<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True)</pre><p>and then we can run Flask server by launching python as</p><pre>venv $ python -m flask run<br> * Debug mode: off<br>WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.<br> * Running on http://127.0.0.1:5000</pre><p>The Flask server is now running locally on port 5000. To verify everything is setup correctly, you can open your browser on <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> or running</p><pre>$ curl http://127.0.0.1:5000/<br>Hey Invoice Generation App!                                                              </pre><p>and in the python console, we will see we received one incoming request</p><pre> * Running on http://127.0.0.1:5000<br>Press CTRL+C to quit<br>127.0.0.1 - - [19/Nov/2024 06:09:23] &quot;GET / HTTP/1.1&quot; 200 -</pre><p>We can now create another endpoint that will receive JSon data and pass those data to our pdf generator script</p><pre>import invoice;<br>from flask import Flask, jsonify, request, json<br><br>app = Flask(__name__)<br><br>@app.route(&quot;/invoice&quot;, methods=[&quot;POST&quot;])<br>def generate_invoice():<br>    <br>    if request.is_json:<br>        data = request.json<br><br>    else:<br>        data = json.loads(request.data)<br><br>    invoice.generate(data);<br>    return jsonify({&#39;message&#39;: &#39;Invoice Generated&#39;}), 204<br></pre><p>What the method does:</p><ul><li>create an endpoint on /invoice resource</li><li>this endpoint allows POST method</li><li>the content of the request body should be JSon data</li><li>we are sending the data to the invoice generator script</li><li>we reply with a HTTP 204 code (content created) and a Json message</li></ul><p>Now, you can restart server and test with postman or insomnia and send a POST request to server</p><pre>curl --request POST \<br>  --url http://127.0.0.1:5000/invoice \<br>  --header &#39;Content-Type: application/json&#39; \<br>  --data &quot;@sample/payload.json&quot;</pre><p>Invoice PDF document is generated on /resources/pdf folder</p><h3>Create Docker image</h3><blockquote>Docker helps developers build, share, run, and verify applications anywhere — without tedious environment configuration or management.</blockquote><p>To have your application running in a docker container, we first need to create a Dockerfile. The docker file (it can be another name but best practices use Dockerfile) is a simple text file with instructions how to build Docker images (the docker image is what will create a Docker container when executed).</p><p>Basically we need to start from scratch (or not) and tell the sytem what it needs to do to have our application running.</p><p>When I said you can start from scratch (a bare OS) or not (so you can start from existing images where instructions have already been executed)</p><p>In our case, we can start from existing python images so we know we will have Python running. And from there, we tell docker what it needs to be to have the app running:</p><ul><li>install dependency to have wkhtmltopdf running</li><li>install python dependencies</li><li>run the application</li></ul><p>Install wkhtmltopdf with dependency, <a href="https://wkhtmltopdf.org/downloads.html">the doc</a> mentions to download a stable version (at the time of writing it is <strong>0.12.6 series</strong>)</p><pre>RUN apt-get update &amp;&amp; apt-get install -y wget xfonts-75dpi fontconfig libjpeg62-turbo libx11-6 libxcb1 libxext6 libxrender1 xfonts-base<br>RUN wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.buster_amd64.deb \<br>    &amp;&amp; dpkg -i wkhtmltox_0.12.6-1.buster_amd64.deb \<br>    &amp;&amp; apt --fix-broken install</pre><p>For python dependencies, it is best practice to create a requirements.txt file with all libraries required, we can create the file with the already installed packages</p><pre>venv $ pip freeze &gt; requirements.txt</pre><p>and in our dockerfile we will tell to copy the requirements file in the image and run the install command</p><pre>COPY ./requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt</pre><p>Then, we need to make sure all files are copied on the image and we can execute the python command</p><pre>COPY ./ .<br>EXPOSE 5001<br>CMD [ &quot;python3&quot;, &quot;-m&quot; , &quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;, &quot;--port=5001&quot;]</pre><p>All together, we indicate that we start from existing image and we will work in the /app directory of the image</p><pre>FROM python:3.11-slim-buster<br><br>WORKDIR /app<br><br>RUN apt-get update &amp;&amp; apt-get install -y wget xfonts-75dpi fontconfig libjpeg62-turbo libx11-6 libxcb1 libxext6 libxrender1 xfonts-base<br>RUN wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.buster_amd64.deb \<br>    &amp;&amp; dpkg -i wkhtmltox_0.12.6-1.buster_amd64.deb \<br>    &amp;&amp; apt --fix-broken install<br>COPY ./requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY ./ .<br><br>EXPOSE 5001<br><br>CMD [ &quot;python3&quot;, &quot;-m&quot; , &quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;, &quot;--port=5001&quot;]</pre><h4>Local docker deployment</h4><p>Now we need to <a href="https://docs.docker.com/get-started/docker-concepts/building-images/build-tag-and-publish-an-image/">build</a> the image</p><pre>$ docker build . --tag &#39;invoice-generator&#39;<br>[+] Building 3.0s (13/13) FINISHED                                   docker:desktop-linux<br> =&gt; [internal] load build definition from Dockerfile                                 0.0s<br> ...<br><br>$ docker image list<br>REPOSITORY                 TAG       IMAGE ID       CREATED              SIZE<br>invoice-generator          latest    xxxxxxxxxxxx   xxxxxxxx             330MB</pre><p>The image is now in your local registry, if you want to have an instance of a container running, you need to run the image</p><pre>$ docker run -it -p 5001:5001 invoice-generator<br> * Debug mode: off<br>WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.<br> * Running on all addresses (0.0.0.0)<br> * Running on http://127.0.0.1:5001<br> * Running on http://172.17.0.2:5001<br>Press CTRL+C to quit</pre><p>In the Dockerfile we had `EXPOSE` docker command that lets you bind container’s port to some port on the host machine but it doesn’t do anything else. When running container, to bind ports specify -p option.</p><p>In our case, we expose port 5001. After building the image when we run the container, run docker with option -p 5001:5001. This binds container’s port 5001 to our laptop/computers port 5001 and that port forwarding lets container to receive outside requests.</p><p>We can verify that everything is working by running</p><pre>$ curl http://127.0.0.1:5001/<br>Hey Invoice Generation App!</pre><p>This concludes this article, so we quickly saw how we can turn a python script to generate PDF document into a microservice running on docker which accepts to receive the JSon data from an API endpoint.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d123d7fbcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate PDF Invoice from HTML Template using Python and Jinja engine]]></title>
            <link>https://medium.com/@frederic.henri/generate-pdf-invoice-from-html-using-python-and-jinja-08fb401a90e3?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/08fb401a90e3</guid>
            <category><![CDATA[jinja2]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 10:18:32 GMT</pubDate>
            <atom:updated>2026-06-15T06:38:43.831Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, we’ll explore how we can use Python to generate PDF Invoices from HTML template using Jinja template engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*klhYIWl1m_2WwQlC" /><figcaption>Photo by <a href="https://unsplash.com/@omerhaktan?utm_source=medium&amp;utm_medium=referral">Ömer Haktan Bulut</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In large application, it is sometimes require to generate PDF documents, there are multiple and different ways to achieve the creation of PDF document, here we will explore how to generate/convert them using a HTML document.</p><p>Here are the features that we will go through:</p><ul><li>Python utility to generate document</li><li>Getting data through JSon data</li><li>HTML template with <a href="https://jinja.palletsprojects.com/en/stable/">Jinja engine</a></li><li>PDF generation (custom fonts, layout …) using <a href="https://wkhtmltopdf.org/">wkhtmltopdf</a></li><li>Alternative: IronPDF for Python</li></ul><p>You can follow using the code from the <a href="https://github.com/fhenri/invoicePDFGenerator">github repo</a>.</p><h4>The tools and libs we are going to use</h4><h4>what is wk&lt;html&gt;to&lt;pdf&gt;</h4><blockquote><strong><em>wkhtmltopdf</em></strong> is an open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely &quot;headless&quot; and do not require a display or display service.</blockquote><h4>what is Jinja ?</h4><blockquote><strong><em>Jinja</em></strong> is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document.</blockquote><h3>The Process</h3><p>The process will look like below:</p><p>we are taking an HTML template and a dataset. Jinja will generate the HTML replacing placeholders with our actual data. This generated HTML will be input for wkhtmltopdf that will render the final PDF document</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rU-PctynZhFnrqIxRFuMg.png" /><figcaption>PDF Generation Process</figcaption></figure><h3>Getting the invoice template document</h3><p>The template will be an HTML document, you can create one yourself, you can download one from internet. In my case, I was using Zoho invoices and I kept the same template that it was using so I downloaded the html and associated css.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gi3ktmqeVS8dO5Lr6_Vsxg.png" /></figure><p>we’ll create a /resources directory where we will get all html and assets as well as generated pdf.</p><ul><li>resources/template will contain our html template document.</li><li>resources/out will contain the generated html document using jinja.</li></ul><p>Since the 2 documents (template and generated) will share some assets (css, images …) we will put all those assets in</p><ul><li>resources/assets will contain all asset for HTML (template and generated document)</li><li>resources/pdf will contain the final PDF document</li></ul><h3>Python script</h3><p>Working with python, it is always good practice to first create your <a href="https://docs.python.org/3/library/venv.html">virtual environment</a>, there are multiple ways but I use venv</p><pre>$ python3 -m venv venv<br>$ source venv/bin/activate<br>venv $ python --version<br>Python 3.12.6</pre><p>The we can install the Jinja package</p><pre>venv $ pip install Jinja2</pre><h4>Jinja template engine</h4><p>The basic with Jinja is that your html will contain placeholders that Jinja will replace with values you will pass.</p><p>First, we need to tell Jinja where to get the template, it will be the invoice.html document in the the resources/templates folder</p><pre>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    invoice_zoho_template = environment.get_template(&quot;invoice.html&quot;)</pre><p>The HTML code contains placeholders such as</p><pre>&lt;span&gt;<br>    &lt;b&gt;{{ customer.name }}&lt;/b&gt;<br>&lt;/span&gt;<br>&lt;span&gt;<br>    &lt;div&gt;{{ customer.address }}&lt;/div&gt;<br>    &lt;div&gt;{{ customer.city }}&lt;/div&gt;<br>    &lt;div&gt;{{ customer.state }}&lt;/div&gt;<br>    &lt;div&gt;{{ customer.country }}&lt;/div&gt;<br>    &lt;div&gt;{{ customer.tax_code }}&lt;/div&gt;<br>&lt;/span&gt;</pre><p>and then we can render the html with</p><pre>invoice_data= {<br>  &quot;customer&quot;: {<br>    &quot;name&quot;: &quot;Inotech&quot;,<br>    &quot;address&quot;: &quot;Paradise Land&quot;,<br>    &quot;city&quot;: &quot;Libreville&quot;,<br>    &quot;state&quot;: &quot;unknown&quot;,<br>    &quot;country&quot;: &quot;France&quot;,<br>    &quot;tax_code&quot;: &quot;FR1234567890&quot;<br>   }<br>}<br>invoice_zoho_template.render(invoice_data)</pre><p>and the HTML result is</p><pre><br>    &lt;span&gt;&lt;b&gt;Inotech&lt;/b&gt;&lt;/span&gt;<br>    &lt;span&gt;<br>      &lt;div&gt;Paradise Land&lt;/div&gt;<br>      &lt;div&gt;Libreville&lt;/div&gt;<br>      &lt;div&gt;unknown&lt;/div&gt;<br>      &lt;div&gt;France&lt;/div&gt;<br>      &lt;div&gt;FR1234567890&lt;/div&gt;<br>    &lt;/span&gt;</pre><p>So if we write the full script and we save the generated HTML in a file, we will get</p><pre>from jinja2 import Environment, FileSystemLoader<br>import os<br><br>def generate ():<br>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    invoice_template = environment.get_template(&quot;invoice.html&quot;)<br><br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;out&quot;), exist_ok=True)<br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;pdf&quot;), exist_ok=True)<br><br>    html_filename = f&quot;resources/out/invoice.html&quot;<br>    with open(html_filename, mode=&quot;w&quot;, encoding=&quot;utf-8&quot;) as results:<br>        invoice_data= {<br>            &quot;customer&quot;: {<br>                &quot;name&quot;: &quot;Inotech&quot;,<br>                &quot;address&quot;: &quot;Paradise Land&quot;,<br>                &quot;city&quot;: &quot;Libreville&quot;,<br>                &quot;state&quot;: &quot;unknown&quot;,<br>                &quot;country&quot;: &quot;France&quot;,<br>                &quot;tax_code&quot;: &quot;FR1234567890&quot;<br>            }<br>        }<br>        results.write(invoice_template.render(invoice_data))<br><br>def main():<br>    generate();<br><br>if __name__ == &quot;__main__&quot;:<br>    main();</pre><p>That’s for the basics, the other main Jinja feature we will use for our PDF Invoices are:</p><ul><li>loop (as we can have invoice for multiple items)</li><li>namespace variables</li><li>Filters and custom filters</li></ul><h4>Jinja loop and namespace variables</h4><p>So generally when you create invoice, you will add a lot of different items and then there will be the sum of each items to be paid.</p><p>To get the total amount, we can either get the amount in python code and pass the amount as a variable to Jinja or we can use <a href="https://jinja.palletsprojects.com/en/stable/templates/#jinja-globals.namespace">global namespace</a>.</p><p>In our HTML code we will get something like (pseudo code) :</p><pre>{% set ns = namespace(amount=0) %}<br><br>&lt;table&gt;<br>  {% for item in items %}<br>  &lt;tr&gt;<br>    &lt;td&gt;{{ item.id }}&lt;/td&gt;<br>    &lt;td&gt;{{ item.description }}&lt;/td&gt;<br>    &lt;td&gt;{{ item.quantity }}&lt;/td&gt;<br>    &lt;td&gt;{{ item.price }}&lt;/td&gt;<br>    &lt;td&gt;{{ item.price * item.quantity }}&lt;/td&gt;<br>  &lt;/tr&gt;<br>  {% set ns.amount = ns.amount + (item.price * item.quantity) %} <br>  {% endfor %}<br>&lt;/table&gt;<br><br>&lt;div&gt;Sub Total:&lt;/div&gt;<br>&lt;div&gt;{{ ns.amount }}&lt;/div&gt;</pre><p>We will also arrange our python code so we can read the json from an input file and pass directly to the render method</p><pre>from jinja2 import Environment, FileSystemLoader<br>import json, os, sys<br><br>def generate (payload):<br>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    invoice_template = environment.get_template(&quot;invoice.html&quot;)<br><br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;out&quot;), exist_ok=True)<br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;pdf&quot;), exist_ok=True)<br><br>    html_filename = f&quot;resources/out/invoice.html&quot;<br>    with open(html_filename, mode=&quot;w&quot;, encoding=&quot;utf-8&quot;) as results:<br>        results.write(invoice_template.render(payload))<br><br>def main():<br>    json_filename = sys.argv[1];<br>    payload = json.load(open(json_filename))<br>    generate(payload);<br><br>if __name__ == &quot;__main__&quot;:<br>    main();</pre><p>so we can produce a document by running</p><pre>$ python invoice.py sample/payload.json</pre><pre>&lt;table&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;1&lt;/td&gt;<br>    &lt;td&gt;monthly support&lt;/td&gt;<br>    &lt;td&gt;20&lt;/td&gt;<br>    &lt;td&gt;700&lt;/td&gt;<br>    &lt;td&gt;14000&lt;/td&gt;<br>  &lt;/tr&gt;<br>  &lt;tr&gt;<br>    &lt;td&gt;2&lt;/td&gt;<br>    &lt;td&gt;on call alerts&lt;/td&gt;<br>    &lt;td&gt;12&lt;/td&gt;<br>    &lt;td&gt;50&lt;/td&gt;<br>    &lt;td&gt;600&lt;/td&gt;<br>  &lt;/tr&gt;<br>&lt;/table&gt;<br>&lt;div&gt;Sub Total:&lt;/div&gt;<br>&lt;div&gt;14600&lt;/div&gt;</pre><p>Additionally we can manage new variables in python and then add those variables when sending to Jinja engine.</p><p>For example, if we have the invoice date and we want to get the invoice due date, we need to add new variables to the payload dictionary</p><pre>    invoice_date = payload[&#39;invoice_date&#39;]<br>    pay_term = payload[&#39;pay_term&#39;] if payload[&#39;pay_term&#39;] else 60<br>    invoice_due_date = (datetime.strptime(invoice_date, &#39;%d-%m-%Y&#39;) + timedelta(days = pay_term)).strftime(&#39;%d-%m-%Y&#39;)<br><br>    html_filename = f&quot;resources/out/test.html&quot;<br>    with open(html_filename, mode=&quot;w&quot;, encoding=&quot;utf-8&quot;) as results:<br>        results.write(invoice_template.render({ <br>                **payload, <br>                &quot;invoice_due_date&quot;: invoice_due_date <br>        }))</pre><h4>Custom filters</h4><blockquote>Filters are Python functions that take the value to the left of the filter as the first argument and produce a new value. Arguments passed to the filter are passed after the value.</blockquote><p>For example, in the Jinja template, we can have</p><pre>{{ &quot;frederic&quot; | capitalize }} # render Frederic</pre><p>There is a set of predefined filters but you can extend by creating your own python methods and have a custom filter to be used in your Jinja template.</p><p>For example, we will add a filter to render amount as a currency object. For this we will install <a href="https://babel.pocoo.org/en/latest/">Babel</a> package. (if you do not know Babel, it is an integrated collection of utilities that assist in internationalizing and localizing Python applications)</p><pre>pip install Babel</pre><p>Then we create a new custom method in python to format a number in a given currency</p><pre>import babel.numbers<br><br>def format_currency_amount(value, currency=&quot;USD&quot;):<br>    pNumber = babel.numbers.format_currency(value, currency, locale=&#39;en_US&#39;)<br>    return pNumber</pre><p>To be able to use this as a filter, we need to add the method in our Jinja environment</p><pre>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    environment.filters[&quot;format_currency&quot;] = format_currency_amount</pre><p>And now, we can use the filter in our template</p><pre>   {{ ns.amount | format_currency(currency) }}</pre><h3>PDF Features</h3><h4>Setup</h4><p>First, we install wkhtmltopdf</p><ul><li>Debian/Ubuntu:</li></ul><pre>$ sudo apt-get install wkhtmltopdf</pre><ul><li>macOS:</li></ul><pre>$ brew install homebrew/cask/wkhtmltopdf</pre><p>Second, we can install python libraries</p><pre>$ pip install pdfkit</pre><p>To test, we just need to add following 2 lines in our code</p><pre>        pdf_filename = f&quot;resources/pdf/invoice.pdf&quot;<br>        pdfkit.from_file(html_filename, pdf_filename)</pre><h4>Document Layout</h4><p>Invoices are somewhat formal document that you will send to your customers, so we should look how we can improve layout.</p><p>The pdfkit package can take a few options to create the pdf document, those options come from the wkhtmltopdf library, the <a href="https://wkhtmltopdf.org/usage/wkhtmltopdf.txt">documentation</a> though is a bit rough</p><blockquote>At the moment, we only have the <a href="https://wkhtmltopdf.org/usage/wkhtmltopdf.txt">auto generated documentation</a> for wkhtmltopdf. This is the same thing you’ll get from running <strong>wkhtmltopdf -H</strong>.</blockquote><p>We can specially define margin on the document. Lets create a dictionnary for the options</p><pre>invoice_generate_options = {<br>    &#39;enable-local-file-access&#39;: None,<br>    &#39;page-size&#39;: &#39;A4&#39;,<br>    &#39;margin-top&#39;: &#39;0in&#39;,<br>    &#39;margin-right&#39;: &#39;0in&#39;,<br>    &#39;margin-bottom&#39;: &#39;0.75in&#39;,<br>    &#39;margin-left&#39;: &#39;0in&#39;,<br>    &#39;encoding&#39;: &quot;UTF-8&quot;,<br>    &#39;no-outline&#39;: None<br>}<br><br>pdfkit.from_file(html_filename, pdf_filename, options=invoice_generate_options) </pre><p>Another option we can use to create a better document is the use of header/footer. With invoices document, there is often the need to include company information (Ids) or country specific invoice requirement.</p><p>We can create a specific HTML document for the footer and reference into the Jinja Environment</p><pre>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    environment.filters[&quot;format_currency&quot;] = format_currency_amount<br>    invoice_template = environment.get_template(&quot;invoice.html&quot;)<br>    footer_template = environment.get_template(&quot;footer.html&quot;)<br><br>    invoice_generate_options = {<br>        &#39;enable-local-file-access&#39;: None,<br>        &#39;page-size&#39;: &#39;A4&#39;,<br>        &#39;margin-top&#39;: &#39;0in&#39;,<br>        &#39;margin-right&#39;: &#39;0in&#39;,<br>        &#39;margin-bottom&#39;: &#39;0.75in&#39;,<br>        &#39;margin-left&#39;: &#39;0in&#39;,<br>        &#39;encoding&#39;: &quot;UTF-8&quot;,<br>        &#39;footer-html&#39;: footer_template.filename,<br>        &#39;no-outline&#39;: None<br>    }</pre><p>The footer document will be in resources/templates</p><pre>&lt;div&gt;<br>    State Your business registration number and other Identifiers required on invoice<br>&lt;/div&gt;</pre><p>and this mention will be added to all the generated PDF document.</p><h4>Stylesheet HTML document</h4><p>As the template document is an HTML document, we can add CSS styles into the document.</p><pre>&lt;head&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;../assets/style.css&quot; /&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>&lt;/head&gt;<br><br>&lt;span class=&quot;pcs-orgname&quot;&gt;<br>  &lt;b&gt;Acme&lt;/b&gt;<br>&lt;/span&gt;&lt;br /&gt;<br>&lt;span class=&quot;pcs-label&quot;&gt;<br>  &lt;div&gt;42 Universe&lt;/div&gt;<br>  &lt;div&gt;PO Box&lt;/div&gt;<br>  &lt;div&gt;Springfield, New State&lt;/div&gt;<br>  &lt;div&gt;Free World&lt;/div&gt;<br>&lt;/span&gt;<br><br><br>.pcs-orgname {<br>    text-align: justify;<br>    font-size: 16pt;<br>    color: #333333;<br>}<br><br>.pcs-customer-name {<br>    font-size: 9pt;<br>    color: #333333;<br>}<br><br>.pcs-label {<br>    color: #333333;<br>}</pre><p>Just one thing you need to pay attention is the link to your stylesheet file, the generated HTML must still have access to it, so when wkhtmltopdf will render the PDF, it can access both the HTML and the assets (css stylesheet, images …)</p><h4>Custom Fonts</h4><p>If you are using custom fonts, you cannot link google fonts link as all assets must be local for wkhtmltopdf to work correctly.</p><p>You must download the fonts, so for example if you are using Inter font you can download from <a href="https://fonts.google.com/specimen/Inter">https://fonts.google.com/specimen/Inter</a></p><p>You can then save the font file within the assets folder and reference the font</p><pre>@font-face {<br>    font-family: &#39;Inter&#39;;<br>    src: url(https://medium.com/&#39;fonts/Inter-VariableFont_opsz,wght.ttf&#39;) format(&#39;truetype&#39;);<br>}<br><br>.pcs-template {<br>    font-family: Inter, &#39;WebFont-Open Sans&#39; !important;<br>    font-size: 11pt;<br>    color: #333333;<br>    background: #ffffff;<br>}</pre><h4>Final Script</h4><p>Given everything we saw, we can finalize the script, we just add another loop so we treat multiple invoices within the same script</p><pre>from jinja2 import Environment, FileSystemLoader<br>from datetime import datetime, timedelta<br>import babel.numbers<br>import json<br>import os<br>import pdfkit<br>import sys<br><br>def format_currency_amount(value, currency=&quot;USD&quot;):<br>    pNumber = babel.numbers.format_currency(value, currency, locale=&#39;en_US&#39;)<br>    return pNumber<br><br>def generate (payload):<br>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    environment.filters[&quot;format_currency&quot;] = format_currency_amount<br>    invoice_template = environment.get_template(&quot;invoice.html&quot;)<br>    footer_template = environment.get_template(&quot;footer.html&quot;)<br><br>    invoice_generate_options = {<br>        &#39;enable-local-file-access&#39;: None,<br>        &#39;page-size&#39;: &#39;A4&#39;,<br>        &#39;margin-top&#39;: &#39;0in&#39;,<br>        &#39;margin-right&#39;: &#39;0in&#39;,<br>        &#39;margin-bottom&#39;: &#39;0.75in&#39;,<br>        &#39;margin-left&#39;: &#39;0in&#39;,<br>        &#39;encoding&#39;: &quot;UTF-8&quot;,<br>        &#39;footer-html&#39;: footer_template.filename,<br>        &#39;no-outline&#39;: None<br>    }<br><br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;out&quot;), exist_ok=True)<br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;pdf&quot;), exist_ok=True)<br><br>    invoices = payload[&#39;invoices&#39;]<br>    for invoice in invoices:<br><br>        invoice_date = invoice[&#39;invoice_date&#39;]<br>        pay_term = invoice[&#39;pay_term&#39;] if invoice[&#39;pay_term&#39;] else 60<br>        invoice_due_date = (datetime.strptime(invoice_date, &#39;%d-%m-%Y&#39;) + timedelta(days = pay_term)).strftime(&#39;%d-%m-%Y&#39;)<br><br>        invoice_filename = f&quot;{invoice[&#39;id&#39;]}-{invoice[&#39;currency&#39;]}&quot;<br>        html_filename = f&quot;resources/out/{invoice_filename}.html&quot;<br>        with open(html_filename, mode=&quot;w&quot;, encoding=&quot;utf-8&quot;) as results:<br>            # merge the json objects - dictionary unpacking operator<br>            invoice_data = { <br>                **invoice, <br>                &quot;invoice_due_date&quot;: invoice_due_date <br>            }<br>            results.write(invoice_template.render(invoice_data))<br><br>        pdf_filename = f&quot;resources/pdf/{invoice_filename}.pdf&quot;<br>        pdfkit.from_file(html_filename, pdf_filename, options=invoice_generate_options)<br>        os.remove(html_filename);<br><br>def main():<br>    json_filename = sys.argv[1];<br>    payload = json.load(open(json_filename))<br>    generate(payload);<br><br>if __name__ == &quot;__main__&quot;:<br>    main();</pre><h3>Alternative: IronPDF for Python — Chrome Engine, No Intermediate File</h3><p>The wkhtmltopdf + pdfkit setup above works well, and Jinja2 is an excellent choice for invoice templating regardless of which PDF engine you use at the end. Worth being aware of one practical constraint though — wkhtmltopdf is built on a Qt/WebKit rendering engine that is now<a href="https://github.com/wkhtmltopdf/wkhtmltopdf"> officially archived</a> and no longer maintained. The article already notes one of its side effects: Google Fonts don’t work, so you have to download fonts locally. CSS assets have to be local too. And the intermediate HTML file on disk (resources/out/) exists entirely to work around the fact that pdfkit needs a file path, not a string.</p><p><strong>IronPDF</strong> is a Python package that uses a real Chrome rendering engine, so web fonts, remote CSS, and modern layout all work as they do in a browser. And because it accepts an HTML string directly, the intermediate file step disappears entirely.</p><h4>Install</h4><pre>pip install ironpdf</pre><p>One prerequisite to be upfront about: IronPDF for Python runs on top of the IronPDF .NET engine, so you need the<a href="https://dotnet.microsoft.com/en-us/download/dotnet/6.0"> .NET 6.0 runtime</a> installed on your machine. On most servers and containers this is a one-time setup; on Linux it’s apt-get install dotnet-runtime-6.0.</p><h4>The Same Invoice Generator with IronPDF</h4><p>The Jinja2 templating half of the script stays completely unchanged — same Environment, same FileSystemLoader, same render (payload) call. The only part that changes is the PDF generation step at the end. Instead of writing HTML to disk and passing a file path to pdfkit, you pass the rendered HTML string directly to IronPDF:</p><pre>from jinja2 import Environment, FileSystemLoader<br>from datetime import datetime, timedelta<br>from ironpdf import ChromePdfRenderer, HtmlHeaderFooter<br>import babel.numbers<br>import json<br>import os<br>import sys<br><br>def format_currency_amount(value, currency=&quot;USD&quot;):<br>    return babel.numbers.format_currency(value, currency, locale=&#39;en_US&#39;)<br><br>def generate(payload):<br>    environment = Environment(loader=FileSystemLoader(&quot;resources/templates/&quot;))<br>    environment.filters[&quot;format_currency&quot;] = format_currency_amount<br>    invoice_template = environment.get_template(&quot;invoice.html&quot;)<br>    footer_template = environment.get_template(&quot;footer.html&quot;)<br><br>    # IronPDF renderer — reuse across invoices<br>    renderer = ChromePdfRenderer()<br><br>    # Page layout options (same as pdfkit options)<br>    renderer.RenderingOptions.PaperSize = &quot;A4&quot;<br>    renderer.RenderingOptions.MarginTop    = 0<br>    renderer.RenderingOptions.MarginRight  = 0<br>    renderer.RenderingOptions.MarginBottom = 19  # 0.75in in mm<br>    renderer.RenderingOptions.MarginLeft   = 0<br><br>    # Footer — rendered from the same Jinja footer template<br>    footer_html = footer_template.render()<br>    renderer.RenderingOptions.HtmlFooter = HtmlHeaderFooter()<br>    renderer.RenderingOptions.HtmlFooter.HtmlFragment = footer_html<br><br>    os.makedirs(os.path.join(&quot;resources&quot;, &quot;pdf&quot;), exist_ok=True)<br><br>    invoices = payload[&#39;invoices&#39;]<br>    for invoice in invoices:<br><br>        invoice_date = invoice[&#39;invoice_date&#39;]<br>        pay_term = invoice[&#39;pay_term&#39;] if invoice[&#39;pay_term&#39;] else 60<br>        invoice_due_date = (<br>            datetime.strptime(invoice_date, &#39;%d-%m-%Y&#39;) +<br>            timedelta(days=pay_term)<br>        ).strftime(&#39;%d-%m-%Y&#39;)<br><br>        invoice_data = {**invoice, &quot;invoice_due_date&quot;: invoice_due_date}<br><br>        # Render HTML string from Jinja — same as before<br>        html_content = invoice_template.render(invoice_data)<br><br>        # Pass the string directly — no temp file needed<br>        pdf = renderer.RenderHtmlAsPdf(html_content)<br><br>        invoice_filename = f&quot;{invoice[&#39;id&#39;]}-{invoice[&#39;currency&#39;]}&quot;<br>        pdf.SaveAs(f&quot;resources/pdf/{invoice_filename}.pdf&quot;)<br><br>def main():<br>    json_filename = sys.argv[1]<br>    payload = json.load(open(json_filename))<br>    generate(payload)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>What Changed and Why</h4><p><strong>The </strong><strong>resources/out folder is gone.</strong> In the original script, writing the rendered HTML to disk exists purely because pdfkit needs a file path. RenderHtmlAsPdf() accepts a string directly, so the intermediate file step — open(html_filename, mode=”w”), pdfkit.from_file(), os.remove(html_filename) — is removed entirely.</p><p><strong>Google Fonts and remote CSS now work.</strong> Because IronPDF uses a Chrome engine, your invoice template can link directly to Google Fonts:</p><pre>&lt;head&gt;<br>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Inter:wght@400;600&amp;display=swap&quot; rel=&quot;stylesheet&quot; /&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;../assets/style.css&quot; /&gt;<br>&lt;/head&gt;</pre><p>No more downloading font files, no more @font-face with local .ttf paths. Chrome fetches them the same way a browser does.</p><p><strong>The </strong><strong>enable-local-file-access flag isn’t needed.</strong> wkhtmltopdf requires this option because it can’t access local assets by default. IronPDF handles local file resolution automatically when you specify a BasePath:</p><pre>pdf = renderer.RenderHtmlAsPdf(html_content, base_path=&quot;resources/assets&quot;)</pre><h4>Honest Trade-Off</h4><p>pdfkit + wkhtmltopdf is <strong>free and open-source</strong> — if the setup constraints (local fonts, temp files, system binary) aren’t a problem for your environment, it’s a perfectly reasonable stack and above script handles it cleanly.</p><p>IronPDF requires a <strong>commercial license</strong> (free 30-day trial available) and the .NET runtime as a prerequisite — two real dependencies worth considering. The return is Chrome-quality rendering, no system binary to manage, no intermediate files, and the same library covering PDF merging, signing, form filling, and text extraction if those come up later.</p><p>The Jinja2 templating layer — the more interesting half of this article — is identical either way.</p><p>Try IronPDF free for 30 days 👉<a href="https://ironpdf.com/python/"> ironpdf.com/python</a></p><p>👉 <strong>Learn more:</strong><a href="https://ironpdf.com/python/"> IronPDF for Python</a> ·<a href="https://ironpdf.com/python/tutorials/html-to-pdf/"> HTML to PDF in Python</a> ·<a href="https://ironpdf.com/python/blog/using-ironpdf-for-python/python-generate-pdf-report-tutorial/"> Python PDF report tutorial</a> ·<a href="https://ironpdf.com/python/#trial-license"> Free 30-day trial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08fb401a90e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set up Google Oauth Authentication on your NextJS web app]]></title>
            <link>https://javascript.plainenglish.io/setting-up-google-oauth-authentication-on-your-nextjs-web-app-9393badd5c80?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/9393badd5c80</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 17:24:12 GMT</pubDate>
            <atom:updated>2024-11-22T14:14:14.764Z</atom:updated>
            <content:encoded><![CDATA[<p>we’ll review how we can setup authentication in an existing web application using the <a href="https://authjs.dev/">auth.js library</a> and <a href="https://authjs.dev/getting-started/providers/google">Google oauth</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rfsuo7ZjCNYnr2gD" /><figcaption>Photo by <a href="https://unsplash.com/@ries_bosch?utm_source=medium&amp;utm_medium=referral">Ries Bosch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We will take the web application that we did develop in previous article (<a href="https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-i-2393a80a70d0">PartI</a> and <a href="https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-ii-4b536845cd2f">PartII</a>) and we will now setup authentication. As our app consists of pages and APIs, we will secure the admin part both pages and APIs.</p><h3>Setting up Auth.js</h3><p>First we need to install the required library and follow the <a href="https://authjs.dev/getting-started/installation">installation instructions</a></p><p>Note: At the time of writing this article, Auth.js is in process to migration v4 to v5 and as they say</p><blockquote><strong>NextAuth.js version 5</strong> is a major rewrite of the next-auth package, that being said, we introduced as few breaking changes as possible. For all else, this document will guide you through the migration process.</blockquote><pre>npm install next-auth@beta</pre><p>The only environment variable that is mandatory is the AUTH_SECRET. This is a random value used by the library to encrypt tokens and email verification hashes. (See <a href="https://authjs.dev/getting-started/deployment">Deployment</a> to learn more). You can generate one via the official <a href="https://cli.authjs.dev/">Auth.js CLI</a> running:</p><pre>npx auth secret</pre><p>This will also add it to our .env.local file</p><pre>AUTH_SECRET=&quot;IqY......=&quot; # Added by `npx auth`. Read more: https://cli.authjs.dev</pre><p>Next, we will implement the code required by the library to work correctly</p><ol><li>Create the lib/auth.js config file and object. This is where we can control the behaviour of the library and specify custom authentication logic, adapters, etc. For our simple case, we will define the <a href="https://authjs.dev/getting-started/providers/google">Google provider</a></li></ol><pre>import NextAuth from &quot;next-auth&quot;<br>import Google from &quot;next-auth/providers/google&quot;<br> <br>export const { handlers, auth, signIn, signOut } = NextAuth({<br>  providers: [Google],<br>})</pre><p>2. Add a Route Handler under /app/api/auth/[...nextauth]/route.ts</p><pre>import { handlers } from &quot;@/lib/auth&quot;<br>export const { GET, POST } = handlers</pre><p>3. Add a middleware to keep the session alive, this will update the session expiry every time it is called.</p><pre>export { auth as middleware } from &quot;@/lib/auth&quot;</pre><h3>Setting up a Google OAuth 2.0 Client ID</h3><p>Next we need to configure the client. If you are not familiar with the google console, I recommend reading this previous article</p><p><a href="https://medium.com/@frederic.henri/step-by-step-guide-to-create-google-service-account-f8237a02f9a4">Step by step guide to create Google Service Account</a></p><p>Now you can go to <a href="https://console.cloud.google.com/apis/dashboard">https://console.cloud.google.com/apis/dashboard</a></p><p>Before you can create the OAuth client, you need to set the <em>OAuth consent screen</em> under <em>APIs &amp; Services</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQtLX9_RMNJrozJ1LtQZNw.png" /></figure><p>Select External unless you have a Google business account and plan to have the application deployed only for your company users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s78Oau4Ve64S03Pj9alxYA.png" /></figure><p>Fill the required fields. You need to provide the app name, emails of the responsible developers and some test users you can use to test before you publish it live.</p><p>Once the OAuth consent screen is enabled, you can go to <a href="https://console.cloud.google.com/apis/credentials">https://console.cloud.google.com/apis/credentials</a> and select your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Vr5bYPhPaxADGqvMZ-itw.png" /></figure><ol><li>make sure you’re under <em>API &amp; Services / Credentials</em></li><li>Click on <em>Create Credentials</em></li><li>Select <em>OAuth client ID</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GoElt6XXMbMatJFiVdKhA.png" /></figure><ol><li>Make sure to select <em>Web application</em> as application type</li><li>Give it a name</li><li>Add the <em>Authorized URI</em> — At first you can add <a href="http://localhost:3000/">http://localhost:3000</a> and then you’ll add the other URIs where you will deploy</li><li>Add the <em>Authorized redirect URIs</em> — Same, at first you can add <a href="http://localhost:3000/api/auth/callback/google">http://localhost:3000/api/auth/callback/google</a> and then you’ll add other URIs once you have deployed your web application on web.</li><li>Click <em>Create</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RY1CGx9w6pWZljIZqga6Yg.png" /></figure><p>Your client is created, you can download the JSon key and copy those information in the .env.local file</p><pre>AUTH_GOOGLE_ID=&quot;xxx-xxx.apps.googleusercontent.com&quot;<br>AUTH_GOOGLE_SECRET=&quot;GOCSPX-xxxxxx&quot;</pre><h3>Protect API Routes</h3><p>To protect the API we have created, we can wrap the request into auth like below, you will have to repeat for all the API routes that needs to be protected</p><pre>import { auth } from &quot;@/lib/auth&quot;<br><br>export const GET = auth(async (request) =&gt; {<br><br>    if (!request.auth) {<br>        return Response.json({ message: &quot;Not authenticated&quot; }, { status: 401 })<br>    }<br>        <br>    const rooms = await getAllRooms();<br>    return NextResponse.json(<br>        { rooms },<br>        { status: 200 }<br>    )<br>})</pre><h3>Protect Pages</h3><p>Now we need to protect our UI and make sure users signed in when navigating to /admin routes.</p><p>we need to get the auth user (if user), you can call</p><pre>const session = await auth()</pre><p>If you copy that in our existing routes which is currently a client page, you’ll get the following error message</p><p><em>Prevent client components from being async functions. See: https://nextjs.org/docs/messages/no-async-client-componenteslint</em><a href="https://nextjs.org/docs/messages/no-async-client-component"><em>@next/next/no-async-client-component</em></a></p><p>so we switched our AdminPage to be a server component and copy the existing code into a new custom component so we have a light page as</p><pre>&quot;use server&quot;<br><br>import { auth } from &quot;@/lib/auth&quot;<br>import { SignIn, SignOut } from &quot;@/components/admin/auth-components&quot;<br>import ListRoom from &quot;@/components/admin/list-rooms&quot;<br><br>const AdminPage = async () =&gt; {<br>  <br>  const session = await auth()<br>  if (!session?.user) return &lt;SignIn /&gt;<br><br>  return (<br>    &lt;&gt;<br>      &lt;SignOut /&gt;<br>      &lt;ListRoom /&gt;<br>    &lt;/&gt;<br>  )<br><br>};<br><br>export default AdminPage;</pre><p>The SignIn component is a simple big fat <strong>Sign In</strong> button in middle of the page that is just calling the SignIn provider from the Google provider</p><pre>import { signIn } from &quot;@/lib/auth&quot;<br>import { Button } from &quot;@/components/ui/button&quot;<br><br>export function SignIn({<br>  provider,<br>  ...props<br>}: { provider?: string } &amp; React.ComponentPropsWithRef&lt;typeof Button&gt;) {<br>  return (<br>    &lt;div className=&quot;h-screen flex items-center justify-center&quot;&gt;<br>      &lt;form<br>        action={async () =&gt; {<br>          &quot;use server&quot;<br>          await signIn(provider)<br>        }}<br>      &gt;<br>        &lt;Button {...props}&gt;Sign In&lt;/Button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Once logged in, we just add a SignOut button in the admin page to cancel the session</p><pre>import { signOut } from &quot;@/lib/auth&quot;<br>import { Button } from &quot;@/components/ui/button&quot;<br><br>export function SignOut(props: React.ComponentPropsWithRef&lt;typeof Button&gt;) {<br>  return (<br>    &lt;div className=&quot;flex w-full items-end justify-end&quot;&gt;<br>      &lt;form<br>        action={async () =&gt; {<br>          &quot;use server&quot;<br>          await signOut()<br>        }}<br>      &gt;<br>        &lt;Button variant=&quot;ghost&quot; className=&quot;mt-2&quot; {...props}&gt;<br>          Sign Out<br>        &lt;/Button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Manage the restricted routes using a middleware</h3><p>This example app does not have many pages nor many routes so we can go and protect them but on large application, this is not convenient.</p><p>To resolve this, we can <a href="https://authjs.dev/getting-started/session-management/protecting#nextjs-middleware">setup a middleware</a>, create a middleware.ts file</p><pre>import { auth as middleware } from &quot;@/lib/auth&quot;;<br><br>export default middleware((req) =&gt; {<br>    const restrictedRoutes = [<br>        &#39;/admin/&#39;,<br>    ]<br><br>    const restrictedAPIRoutes = [<br>        &#39;/api/admin/&#39;,<br>    ]<br><br>    const isRestrictedRoutes = !!restrictedRoutes.find(route =&gt; req.nextUrl.pathname.startsWith(route.toLowerCase()));<br><br>    if (!req.auth &amp;&amp; isRestrictedRoutes) {<br>        const newUrl = new URL(&quot;/admin&quot;, req.nextUrl.origin);<br>        return Response.redirect(newUrl);<br>    }<br><br>    const isRestrictedAPIRoutes = !!restrictedRoutes.find(route =&gt; req.nextUrl.pathname.startsWith(route.toLowerCase()));<br>    if (!req.auth &amp;&amp; isRestrictedRoutes) {<br>        return Response.json({ message: &quot;Not authenticated&quot; }, { status: 401 })<br>    }<br><br>});</pre><p>All routes under admin requires a signed in user so we are checking the routes and will redirect to /admin if the user is not authenticated</p><p>We do separate the API routes so we can return a JSon message and do not send a redirect on the request.</p><p>This was, everything is managed in central place — This is my preferred way.</p><h3>Deployment</h3><p>Initially when I prepared those articles, I thought about deploying to <a href="https://www.netlify.com/">Netlify</a> (to change from Vercel and test a bit) that is the main reason I was use redis, otherwise I would probably have used Vercel KV.</p><p>Deployment worked fine until I deployed the auth part, I was facing issues on the authentication process. Then I saw on the <a href="https://authjs.dev/getting-started/deployment#auth_trust_host">documentation</a></p><p>AUTH_TRUST_HOST</p><blockquote>When deploying your application behind a reverse proxy, you’ll need to set AUTH_TRUST_HOST equal to true. This tells Auth.js to trust the X-Forwarded-Host header from the reverse proxy. Auth.js will automatically infer this to be true if we detect the environment variable indicating that your application is running on one of the supported hosting providers. Currently VERCEL and CF_PAGES (Cloudflare Pages) are supported.</blockquote><p>I have been trying a bit to play with those variables and change few things, nothing worked great. I then did a quick try on Vercel and things were working like a charm.</p><p>Thanks for reading till there, it has been some long chapters for somewhat a small app but we covered multiple topics.</p><p>Have fun building Web Application!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9393badd5c80" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/setting-up-google-oauth-authentication-on-your-nextjs-web-app-9393badd5c80">Set up Google Oauth Authentication on your NextJS web app</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a fullstack booking meeting room app with NextJS Part II]]></title>
            <link>https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-ii-4b536845cd2f?source=rss-2504ac9e1697------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b536845cd2f</guid>
            <category><![CDATA[shadcn]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Frederic Henri]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 12:20:04 GMT</pubDate>
            <atom:updated>2024-11-25T16:20:07.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a fullstack NextJS booking meeting room app — Part II</h3><p>We will integrate a <a href="https://medium.com/@frederic.henri/building-a-fullstack-booking-meeting-room-app-with-nextjs-part-i-2393a80a70d0">previously created web application</a> with Google <a href="https://developers.google.com/calendar/api/guides/overview">calendars</a> and <a href="https://developers.google.com/calendar/api/v3/reference/events">events</a> APIs. To do we first need to create a Google Service Account</p><p><a href="https://medium.com/@frederic.henri/step-by-step-guide-to-create-google-service-account-f8237a02f9a4">Step by step guide to create Google Service Account</a></p><p>Please follow the above guide if you require one.</p><p>Since we will integrate with both calendars and events, we first need to create a client to manage authentication given the information from the service account.</p><p>Add the following information to the already created .env.local file</p><pre>CALENDAR_ID=<br>GOOGLE_PROJECT_ID=<br>GOOGLE_PRIVATE_KEY_ID=<br>GOOGLE_PRIVATE_KEY=&quot;-----BEGIN PRIVATE KEY-----\n<br>\n-----END PRIVATE KEY-----\n&quot;<br>GOOGLE_CLIENT_EMAIL=<br>GOOGLE_CLIENT_ID=</pre><p>Then we can create a lib/google.ts client file to manage both calendar and events scopes.</p><pre>import { google } from &quot;googleapis&quot;;<br><br>const SCOPES = [<br>  &quot;https://www.googleapis.com/auth/calendar&quot;,<br>  &quot;https://www.googleapis.com/auth/calendar.events&quot;,<br>];<br><br>export const initGoogleCalendar = async () =&gt; {<br>  try {<br>    const credentials = {<br>      client_id: process.env.GOOGLE_CLIENT_ID,<br>      client_email: process.env.GOOGLE_CLIENT_EMAIL,<br>      project_id: process.env.GOOGLE_PROJECT_ID,<br>      // FIX netlify https://stackoverflow.com/a/67516991/4296747<br>      private_key: process.env.GOOGLE_PRIVATE_KEY?.split(&quot;\\n&quot;).join(&quot;\n&quot;)<br>    }<br>    const auth = new google.auth.GoogleAuth({<br>      credentials: credentials,<br>      scopes: SCOPES,<br>    });<br><br>    const calendar = google.calendar({ version: &quot;v3&quot;, auth });<br><br>    return calendar;<br>  } catch (error) {<br>    console.error(&quot;Error initializing Google Calendar API:&quot;, error);<br>  }<br>};</pre><h4>Creating calendar for each room</h4><p>We will create a calendar for each room that is created, so we will not mix up events. When creating the room, we need now to provide a calendar Id that we will have created</p><p>create a services/calendar.ts that will manage the creation of a new Google calendar</p><pre>import { initGoogleCalendar } from &#39;@/lib/google&#39;;<br><br>export const createCalendar = async (<br>    calName: string<br>): Promise&lt;string | null | undefined&gt; =&gt; {<br><br>    const googleClient = await initGoogleCalendar();<br><br>    const calendar = {<br>        summary: calName,<br>    }<br><br>    // review https://developers.google.com/calendar/api/v3/reference/calendars#resource for other available options<br>    const response = await googleClient?.calendars.insert({<br>        requestBody: calendar<br>    })<br>    <br>    return response?.data.id<br>};</pre><p>we can now update the creation of a new room by calling the method and setting the calendarId as room Id</p><pre>import { NextResponse } from &quot;next/server&quot;<br>import { createCalendar } from &#39;@/services/calendar&#39;;<br>import { setRoom, getAllRooms } from &#39;@/services/room&#39;;<br>import { Room } from &#39;@/types/room&#39;;<br><br>export const POST = auth(async (request) =&gt; {<br><br>    const { name, capacity } = await request.json();<br>    if (!name || !capacity) {<br>        return NextResponse.json(<br>            { error: &#39;Missing required fields&#39; },<br>            { status: 400 }<br>        );<br>    }<br><br>    const calendarId = await createCalendar(name)<br>    if (!calendarId) {<br>        return NextResponse.json(<br>            { error: &#39;Missing required fields&#39; },<br>            { status: 400 }<br>        );<br>    }<br><br>    const room: Room = {<br>      id: calendarId,<br>      name,<br>      capacity: parseInt(capacity, 10),<br>    };<br><br>    await setRoom(room);<br>    return NextResponse.json(<br>        { room },<br>        { status: 201 }<br>    );<br><br>})</pre><h3>End User Form</h3><p>The end user form needs to have the following information</p><ul><li>Title and Description (generic from meeting invite)</li><li>The Date and duration (TimeFrom and TimeTo)</li><li>The list of Participants or Guest</li><li>The Room where meeting will take place</li></ul><p>With the above information, the form will look like (you can review code from github for the form but this is pretty standard)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEJPqPGU-o_Sjcta4-A1ZQ.png" /><figcaption>End User Meeting Form</figcaption></figure><p>From there, we now have 2 things to build</p><ul><li>Handle the Create Meeting Invite button</li><li>Generate the list of available rooms based on the date/time and the number of participants</li></ul><p>Lets create the API endpoints for those 2 requests.</p><h3>Scheduling Event API</h3><h4>Create Meeting Endpoint</h4><p>First we create the endpoint to create a new event, create the api/schedule/route.ts file</p><pre>import { type NextRequest, NextResponse } from &#39;next/server&#39;<br>import { createEvent } from &#39;@/services/event&#39;;<br><br>export async function POST(request: NextRequest) {   <br>    const { roomId, title, description, date, timeFrom, timeTo, guests } = await request.json();<br>    const event = await createEvent(<br>        roomId,<br>        title, <br>        description,<br>        date,<br>        timeFrom,<br>        timeTo,<br>        guests<br>    )<br><br>    return NextResponse.json(<br>        { event },<br>        { status: 200 }<br>    )<br>}</pre><p>Lets create the services/events file to create a new event</p><pre>import { initGoogleCalendar } from &#39;@/lib/google&#39;;<br>import { parse, formatISO, add } from &quot;date-fns&quot;;<br><br>export const createEvent = async (<br>    roomId: string,<br>    title: string,<br>    description: string,<br>    date: string,<br>    timeFrom: string,<br>    timeTo: string,<br>    guests: string[],<br>  ) =&gt; {<br>    const googleClient = await initGoogleCalendar();<br>    const startTime = parse(`${date} ${timeFrom}`, &#39;yyyy-MM-dd HH:mm&#39;, new Date());<br>    const endTime = parse(`${date} ${timeTo}`, &#39;yyyy-MM-dd HH:mm&#39;, new Date());<br>    <br>    const event = {<br>      summary: title,<br>      description: description,<br>      start: {<br>        dateTime: formatISO(startTime),<br>        timeZone: &quot;UTC&quot;,<br>      },<br>      end: {<br>        dateTime: formatISO(endTime),<br>        timeZone: &quot;UTC&quot;,<br>      },<br>      //Service accounts cannot invite attendees without Domain-Wide Delegation of Authority.<br>      //attendees: guests.map(guest =&gt; ({ email: guest })),<br>      //sendUpdates: &#39;all&#39;,<br>      conferenceData: {<br>        createRequest: {<br>          requestId: Math.random().toString(36).substring(7),<br>          conferenceSolutionKey: {<br>            type: &quot;hangoutsMeet&quot;,<br>          },<br>        },<br>      },<br>      reminders: {<br>        // you can add this if you want to override the calendar reminder.<br>        useDefault: false,<br>        overrides: [<br>          {<br>            method: &quot;email&quot;,<br>            minutes: 30,<br>          },<br>        ],<br>      },<br>    };<br>  <br>    const meeting = await googleClient?.events.insert({<br>      calendarId: roomId,<br>      //conferenceDataVersion: 1,<br>      requestBody: event,<br>    })<br><br>    let message = &quot;&quot;<br>    if (meeting?.data) {<br>      if (meeting.status === 200) {<br>        message = &quot;Meeting has been added to the calendar&quot;;<br>      } else {<br>        console.log(&quot;Failed to insert event&quot;);<br>        message = &quot;Failed to insert event&quot;;<br>      }<br>    } else {<br>      console.log(&quot;Failed to insert event: Calendar not initialized&quot;);<br>      message = &quot;Failed to insert event: Calendar not initialized&quot;;<br>    }<br>    <br>    return { message: message };<br>};</pre><h4>Get the list of available room</h4><p>You can query based on capacity and date/time to get the list of available rooms</p><pre>import { type NextRequest, NextResponse } from &#39;next/server&#39;<br>import { getAvailableRoom } from &#39;@/services/room&#39;;<br><br>export async function GET (request: NextRequest) {<br>    const searchParams = request.nextUrl.searchParams<br><br>    const capacity = searchParams.get(&quot;capacity&quot;) || undefined<br>    const date = searchParams.get(&quot;date&quot;) || undefined<br>    const timeFrom = searchParams.get(&quot;timeFrom&quot;) || undefined<br>    const timeTo = searchParams.get(&quot;timeTo&quot;) || undefined<br><br>    const rooms = await getAvailableRoom(date, timeFrom, timeTo, capacity);<br><br>    return NextResponse.json(<br>        { rooms },<br>        { status: 200 }<br>    )<br>}</pre><p>in the services/room.ts we add a new method. First we filter based on the capacity and exclude all rooms that do not meet this first criteria, then we get the list of all events on this date and exclude the rooms where there is already a meeting during the requested time.</p><pre>export const getAvailableRoom = async (<br>  date?: string, <br>  timeFrom?: string,<br>  timeTo?: string,<br>  capacity?: string,<br>): Promise&lt;Room[]&gt; =&gt; {<br><br>  let rooms = await getAllRooms()<br><br>  // we first filter on capacity and remove room with not enough seats<br>  if (capacity) {<br>    rooms = rooms.filter(room =&gt; room.capacity &gt;= parseInt(capacity, 10));<br>  }<br><br>  const startTime = parse(`${date} ${timeFrom}`, &#39;yyyy-MM-dd HH:mm&#39;, new Date());<br>  const endTime = parse(`${date} ${timeTo}`, &#39;yyyy-MM-dd HH:mm&#39;, new Date());<br><br>  // deal with async code<br>  const roomPromises = rooms.map(async room =&gt; {<br>    const events = await listEvent(room.id, date, 1)<br>    const hasConflict = events.some((event: googleCalendar.Schema$Event) =&gt; {<br>      const eventStart = new Date(event.start?.dateTime || &#39;&#39;);<br>      const eventEnd = new Date(event.end?.dateTime || &#39;&#39;);<br>      return isBefore(startTime, eventEnd) &amp;&amp; isAfter(endTime, eventStart)<br>    })<br>    return { room, hasConflict };<br>  })<br><br>  const roomResults = await Promise.all(roomPromises);<br>  rooms = roomResults.filter(({ hasConflict }) =&gt; !hasConflict).map(({ room }) =&gt; room);<br><br>  return rooms;<br>}</pre><h4>Adding handler in the End User Form</h4><p>Now you can add the handler when changing date/time information or number of guest from the End User Form to get the list of available room and display the list in the drop down selection</p><pre>&#39;use client&#39;<br><br>import { useState } from &#39;react&#39;<br>import { useToast } from &quot;@/hooks/use-toast&quot;<br><br>export default function MeetingInviteForm() {<br>  const [guests, setGuests] = useState&lt;string[]&gt;([])<br>  const [newGuest, setNewGuest] = useState(&#39;&#39;)<br>  const [rooms, setRooms] = useState&lt;Room[]&gt;([])<br>  const [selectedRoom, setSelectedRoom] = useState&lt;string&gt;()<br>  const [isDataLoading, setIsDataLoading] = useState(true);<br>  <br>  const { toast } = useToast()<br><br>  const checkAvailableRoom = async (<br>    capacity: number<br>  ) =&gt; {<br>    setIsDataLoading(true)<br><br>    const dateElement = document.getElementById(&#39;date&#39;) as HTMLInputElement;<br>    const timeFromElement = document.getElementById(&#39;timeFrom&#39;) as HTMLInputElement;<br>    const timeToElement = document.getElementById(&#39;timeTo&#39;) as HTMLInputElement;<br>  <br>    const params = new URLSearchParams({<br>      &#39;capacity&#39;: capacity.toString(),<br>      &#39;date&#39;: dateElement?.value,<br>      &#39;timeFrom&#39;: timeFromElement?.value,<br>      &#39;timeTo&#39;: timeToElement?.value,<br>    });<br><br>    const response = await fetch(`/api/schedule?${params}`);<br>    const data = await response.json();<br>    setRooms(data.rooms);<br>    setIsDataLoading(false)<br>  }<br><br>....<br>          &lt;div className=&quot;space-y-2&quot;&gt;<br>            &lt;Label htmlFor=&quot;date&quot;&gt;Date&lt;/Label&gt;<br>            &lt;Input id=&quot;date&quot; type=&quot;date&quot; onChange={() =&gt; checkAvailableRoom(guests.length)} required /&gt;<br>          &lt;/div&gt;<br>....<br>              &lt;SelectGroup&gt;<br>                &lt;SelectLabel&gt; -- Available Room -- &lt;/SelectLabel&gt;<br>                {isDataLoading ? (<br>                &lt;div className=&quot;flex flex-col justify-center items-center h-32&quot;&gt;<br>                  &lt;div className=&quot;animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700&quot;&gt;&lt;/div&gt;<br>                  &lt;p className=&quot;ml-2 justify-center items-center&quot;&gt;Loading...&lt;/p&gt;<br>                &lt;/div&gt;<br>                ) : (rooms &amp;&amp; rooms.map((room) =&gt; (<br>                  &lt;SelectItem key={room.id} value={room.id}&gt;<br>                    { room.name }<br>                  &lt;/SelectItem&gt;))<br>                )}                <br>              &lt;/SelectGroup&gt;</pre><p>The second handler is when submitting the form</p><pre>...<br>  const createMeeting = async () =&gt; {<br>    setIsMeetingCreation(true)<br><br>    const titleElement = document.getElementById(&#39;title&#39;) as HTMLInputElement;<br>    const dateElement = document.getElementById(&#39;date&#39;) as HTMLInputElement;<br>    const timeFromElement = document.getElementById(&#39;timeFrom&#39;) as HTMLInputElement;<br>    const timeToElement = document.getElementById(&#39;timeTo&#39;) as HTMLInputElement;<br>    const descriptionElement = document.getElementById(&#39;description&#39;) as HTMLInputElement;<br>    <br>    if (!dateElement.value || !titleElement.value || !timeFromElement.value || !selectedRoom) {<br>      toast({<br>        variant: &quot;destructive&quot;,<br>        title: &quot;Meeting created successfully&quot;,<br>        description: &quot;Make sure to fill in all required fields&quot;,<br>      })<br>      setIsMeetingCreation(false)<br>      return;<br>    }<br><br>    const meetingData = {<br>      title: titleElement?.value,<br>      date: dateElement?.value,<br>      timeFrom: timeFromElement?.value,<br>      timeTo: timeToElement?.value,<br>      description: descriptionElement?.value,<br>      guests: guests,<br>      roomId: selectedRoom,<br>    };<br><br>    const response = await fetch(&#39;/api/schedule&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body: JSON.stringify(meetingData),<br>    });<br><br><br>    setIsMeetingCreation(false)<br>    const result = await response.json();<br><br>    // Reset form fields<br>    setGuests([]);<br>    setNewGuest(&#39;&#39;);<br>    setSelectedRoom(&#39;&#39;); <br>    <br>    titleElement.value = &#39;&#39;;<br>    dateElement.value = &#39;&#39;;<br>    timeFromElement.value = &#39;&#39;;<br>    timeToElement.value = &#39;&#39;;<br>    descriptionElement.value = &#39;&#39;;<br>    <br>    toast({<br>      title: &quot;Meeting created successfully&quot;,<br>      description: result.event.message,<br>    })<br>  }<br>...<br>        &lt;Button type=&quot;submit&quot; className=&quot;w-full inline-flex items-center px-5 py-2.5 mt-4 sm:mt-6 text-sm font-medium text-center&quot; onClick={createMeeting} disabled={isMeetingCreation}&gt;<br>          { isMeetingCreation ? &lt;&gt;&lt;ReloadIcon className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;Please wait ...&lt;/&gt;<br>          : &quot;Create Meeting Invite&quot; }<br>        &lt;/Button&gt;<br>...</pre><h3>Updating Admin Page to get the list of all meeting</h3><p>From the admin datatable, we will add a link to a new page that will display the details of the room’s events.</p><pre>....<br>  {<br>    id: &quot;view&quot;,<br>    enableHiding: false,<br>    //cell: ({ row }) =&gt; {<br>    cell: function Cell({ row }) {<br>      return (<br>        &lt;Link href={{<br>                pathname: &#39;/admin/schedule&#39;,<br>                query: { room: row.original.id },<br>              }}&gt;<br>                &lt;CalendarDays className=&quot;ml-2 h-4 w-4&quot;/&gt;<br>        &lt;/Link&gt;<br>      )<br>    },<br>  },<br>....</pre><h4>Admin Scheduling Event API</h4><p>we will need to create some admin endpoints to work with events. We need to be able to get the list of events for one room, and to delete an event:</p><pre>import { NextResponse } from &quot;next/server&quot;<br>import { auth } from &quot;@/lib/auth&quot;<br>import { listEvent, deleteEvent } from &#39;@/services/event&#39;;<br><br>export const GET = auth(async (request) =&gt; {<br>    const searchParams = request.nextUrl.searchParams<br>    const roomId = searchParams.get(&quot;roomId&quot;)<br><br>    if (!roomId) {<br>        return NextResponse.json(<br>            { error: &#39;Missing required fields&#39; },<br>            { status: 400 }<br>        );<br>    }<br><br>    const startDate = searchParams.get(&quot;startDate&quot;) || undefined<br>    const schedules = await listEvent(roomId, startDate);<br>    return NextResponse.json(<br>        { schedules },<br>        { status: 200 }<br>    )<br>})<br><br>export const DELETE = auth(async (request) =&gt; {<br>    const searchParams = request.nextUrl.searchParams<br>    const roomId = searchParams.get(&quot;roomId&quot;)<br>    const eventId = searchParams.get(&quot;eventId&quot;)<br><br>    if (!roomId || !eventId) {<br>        return NextResponse.json(<br>            { error: &#39;Missing required fields&#39; },<br>            { status: 400 }<br>        );<br>    }<br><br>    const schedules = await deleteEvent(roomId, eventId);<br>    return NextResponse.json(<br>        { schedules },<br>        { status: 200 }<br>    )<br>})</pre><pre>export const listEvent = async (<br>  roomId: string,<br>  startDate?: string | undefined,<br>  duration = 7<br>) =&gt; {<br><br>  const googleClient = await initGoogleCalendar();<br><br>  let timeMin = formatISO(new Date())<br>  if (startDate) {<br>    timeMin = parse(startDate, &#39;yyyy-MM-dd&#39;, new Date()).toISOString()<br>  }<br><br>  const response = await googleClient?.events.list({<br>    calendarId: roomId,<br>    eventTypes: [&quot;default&quot;],<br>    timeMin: timeMin,<br>    timeMax: add(timeMin, { days: duration }).toISOString(),<br>    singleEvents: true,<br>    orderBy: &#39;startTime&#39;,<br>  })<br><br>  const events = response?.data?.items || [];<br>  return events;<br>}</pre><h4>Enhancing the Admin UI</h4><p>For the schedule page, we will work with the <a href="https://doc.daypilot.org/calendar/react/">day-pilot library</a>,</p><pre>npm install @daypilot/daypilot-lite-react</pre><p>The schedule page will look like below, we will display the <a href="https://doc.daypilot.org/calendar/week-view/">week view</a> and a date picker (based on <a href="https://ui.shadcn.com/docs/components/calendar">shadcn calendar component</a>) so we can change the schedule view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqC1IOr1o6pg2jB5y7_D8w.png" /></figure><p>Lets define the 2 main components of the page</p><pre>const ScheduleForm = () =&gt; {<br>    const searchParam = useSearchParams();<br>    const roomId = searchParam.get(&quot;room&quot;)!;<br>    const [date, setDate] = React.useState&lt;Date&gt;(new Date())<br>    const [isDataLoading, setIsDataLoading] = useState(true);<br><br>    return (<br>        &lt;div className=&quot;container mx-auto py-10&quot;&gt;<br>            &lt;h2 className=&quot;mb-2 text-xl font-bold text-gray-900 dark:text-white&quot;&gt;<br>            Review Meeting Room Schedule<br>            &lt;/h2&gt;<br>            &lt;div className=&quot;flex flex-col items-center space-y-4&quot;&gt;<br>                &lt;CalendarView roomId={ roomId } startDate={ date } setIsDataLoading={ setIsDataLoading }/&gt;<br>                &lt;div className=&quot;content-center&quot;&gt;<br>                    &lt;DatePicker date={date} onDateChange={setDate} isDataLoading={isDataLoading} /&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    )<br>}<br><br>const SchedulePage = () =&gt; {<br>    return (<br>        &lt;Suspense&gt;<br>            &lt;ScheduleForm /&gt;<br>        &lt;/Suspense&gt;<br>    )<br>}</pre><p>The CalendarView component will fetch all events for the room starting a specific date by calling the new schedule endpoint</p><pre>const CalendarView = ({<br>  roomId,<br>  startDate,<br>  setIsDataLoading,<br>}: {<br>  roomId: string;<br>  startDate: Date;<br>  setIsDataLoading: (loading: boolean) =&gt; void;<br>}) =&gt; {<br>  const [calendar, setCalendar] = useState(null);<br>  const [events, setEvents] = useState&lt;RoomEvent[]&gt;([]);<br><br>  const startWeek = format(startOfWeek(startDate), &quot;yyyy-MM-dd&quot;);<br><br>  const fetchEvents = async () =&gt; {<br>    setIsDataLoading(true);<br>    const params = new URLSearchParams({<br>      roomId: roomId,<br>      startDate: startWeek,<br>    });<br>    const response = await fetch(`/api/admin/schedule?${params}`);<br>    const data = await response.json();<br>    const filteredEvents = data.schedules.map(<br>      (schedule: googleCalendar.Schema$Event) =&gt; ({<br>        id: schedule.id,<br>        text: schedule.summary,<br>        start: schedule.start?.dateTime,<br>        end: schedule.end?.dateTime,<br>      })<br>    );<br>    setEvents(filteredEvents);<br>    setIsDataLoading(false);<br>  };<br><br>  useEffect(() =&gt; {<br>    fetchEvents();<br>  }, [startDate]);<br><br><br>  return (<br>    &lt;DayPilotCalendar<br>      viewType={&quot;Week&quot;}<br>      startDate={startWeek}<br>      timeRangeSelectedHandling={&quot;Enabled&quot;}<br>      events={events}<br>      controlRef={setCalendar}<br>    /&gt;<br>  );<br>};</pre><p>That will display all events during a week. We can improve the UI by adding the possibility for admin users to delete an event by clicking on it and calling the delete endpoint</p><pre>  const onEventClick = async (args: DayPilot.CalendarEventClickArgs) =&gt; {<br>    if (!calendar) return; // Ensure calendar is set<br>    const e = args.e;<br><br>    const modal = await DayPilot.Modal.confirm(`Delete event&lt;br/&gt; ${e.text()}`);<br><br>    if (!modal.result) {<br>      return;<br>    }<br>    setIsDataLoading(true);<br><br>    const eventId = e.data.id;<br>    const params = new URLSearchParams({<br>      roomId: roomId,<br>      eventId: eventId,<br>    });<br>    const response = await fetch(`/api/admin/schedule?${params}`, {<br>      method: &quot;DELETE&quot;,<br>    });<br><br>    if (response.ok) {<br>      setEvents((prevEvents) =&gt;<br>        prevEvents.filter((event) =&gt; event.id !== eventId)<br>      );<br>    }<br><br>    setIsDataLoading(false);<br>  };<br><br>  return (<br>    &lt;DayPilotCalendar<br>      viewType={&quot;Week&quot;}<br>      startDate={startWeek}<br>      timeRangeSelectedHandling={&quot;Enabled&quot;}<br>      events={events}<br>      onEventClick={onEventClick}<br>      controlRef={setCalendar}<br>    /&gt;<br>  );<br>};</pre><p>The second component of the page is a date picker, when we change the date, we display the usual load spinner while the date will be fetched on the main component</p><pre>const DatePicker = ({<br>  date,<br>  onDateChange,<br>  isDataLoading,<br>}: {<br>  date: Date | undefined;<br>  onDateChange: (date: Date) =&gt; void;<br>  isDataLoading: boolean;<br>}) =&gt; {<br>  return (<br>    &lt;Popover&gt;<br>      &lt;PopoverTrigger asChild&gt;<br>        &lt;Button<br>          variant={&quot;outline&quot;}<br>          className={cn(<br>            &quot;w-[280px] justify-start text-left font-normal&quot;,<br>            !date &amp;&amp; &quot;text-muted-foreground&quot;<br>          )}<br>        &gt;<br>          {isDataLoading ? (<br>            &lt;&gt;<br>              &lt;div className=&quot;animate-spin rounded-full h-5 w-5 border-b-2 border-blue-700&quot;&gt;&lt;/div&gt;<br>              &lt;p className=&quot;ml-2 justify-center items-center&quot;&gt;Loading...&lt;/p&gt;<br>            &lt;/&gt;<br>          ) : (<br>            &lt;&gt;<br>              &lt;CalendarIcon className=&quot;mr-2 h-4 w-4&quot; /&gt;<br>              {date ? format(date, &quot;PPP&quot;) : &lt;span&gt;Pick a date&lt;/span&gt;}<br>            &lt;/&gt;<br>          )}<br>        &lt;/Button&gt;<br>      &lt;/PopoverTrigger&gt;<br>      &lt;PopoverContent className=&quot;w-auto p-0&quot;&gt;<br>        &lt;Calendar<br>          mode=&quot;single&quot;<br>          selected={date}<br>          onSelect={(date) =&gt; {<br>            if (date) {<br>              onDateChange(date);<br>            }<br>          }}<br>          initialFocus<br>        /&gt;<br>      &lt;/PopoverContent&gt;<br>    &lt;/Popover&gt;<br>  );<br>};</pre><p>Thats it! You have a fully functional booking app, you can use this as a template for any kind of booking (it can be meeting room, holiday apartment …)</p><p>I hope you learnt something valuable from the article, if you have any suggestion or making any good use of it, let me know, I am always interested to see how creative people can be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b536845cd2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>