Supply Chain Management Strategies with R and Shiny

Reading time:
time
min
By:
Eduardo Almeida
October 20, 2022

During the pandemic, the supply chain and its management strategy burst into the spotlight. Supply chain management (SCM) became a household topic as its disruptions began to directly impact people's lives and the global economy.

But the truth is, good supply chain strategies are the ones that are aligned with business strategy. And in this complex environment, there is a trade-off between responsive versus efficient strategies.
<ul><li><a href="#RSCM">Spreadsheets, R, and Supply Chain Management</a></li><li><a href="#strategy">Strategy and the Supply Chain</a></li><li><a href="#overview">Supply Chain Overview</a></li><li><a href="#models">R and Supply Chain Models</a></li><li><a href="#usecase">Supply Chain Management in R use case</a></li><li><a href="#sharing">Sharing results using R Shiny</a></li></ul>

<hr />

<h2 id="RSCM">Spreadsheets, R, and Supply Chain Management</h2>
A spreadsheet solution enables a lot of flexibility but it comes at the expense of reproducibility and error pruning. ERP is a very mature system and has strict rules that make it reliable and efficient but adds little opportunity for newer designs.

This is an extreme example, but it’s a valid one:

Where IT products are not flexible enough nor have the required development speed for business needs, having spreadsheet solutions where an IT product should be used is a common source of strategy misalignment. And one that causes visibility issues in the supply chain.

This is where R comes into play. It’s great for solutions that require a certain degree of development speed and flexible design but are also reproducible with the building blocks of IT maturity. Knowing the requirements that allow an R solution to shine also depends on a proper understanding of where you stand with IT requirements and the business environment.

In this post, we depict the general understanding of business strategy and supply chain as a subsidy to strategic alignment and why using R sustains the visibility and reproducibility required for SCM strategy.

We'll also show use cases for R and Shiny in SCM and how to add additional value. 

<hr />

<h2 id="strategy">Strategy and the Supply Chain</h2>
Porter has a great definition of strategy: "the creation of fit between activities, where each activity is consistent, mutually reinforcing, and the fit is done optimally for competitive advantage."

<img class="size-full wp-image-16256 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc087a667cfae8d9756_strategy.webp" alt="" width="717" height="342" />

This fit can have different perspectives such as:
<ul><li style="font-weight: 400;" aria-level="1">Internal fit: Organization structure</li><li style="font-weight: 400;" aria-level="1">External fit: Competition</li><li style="font-weight: 400;" aria-level="1">Dynamic fit: Demand behavior </li></ul>
Also, Shapiro and Heskett state that strategy has a set of dichotomies that creates tension on each perspective, therefore, strategy decisions will always inherit a set of trade-offs.

<img class="size-full wp-image-16266 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc1569a8a6eb892fe14_supply-chain-management-strategy-trade-offs.webp" alt="" width="615" height="285" />

This is an extensive field, and for this post, this is an essential concept. If you want to go further, I highly recommend Wharton's free  Strategic Management program.
<h2 id="overview">Supply Chain Overview</h2>
The supply chain is a big topic and can be explained through a variety of viewpoints. Below is a condensed summary of the SCOR Model and other descriptions. 

<img class="size-full wp-image-16258 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc39506383404c33d20_suply-chain-SCORE-model.webp" alt="Supply Chain Score model" width="1117" height="364" />

An additional summation:

<img class="size-full wp-image-16244 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc3923c12912d3f3b20_Chris-Caplice-quote-supply-chain-is-the-art-and-science.webp" alt="Supply Chain Management is an art" width="1269" height="187" />
<h3>Strategic fit in the Supply Chain</h3>
A strategic fit occurs when the competitive strategy and supply chain strategy align goals. Its success is connected to several factors:
<ol><li style="font-weight: 400;" aria-level="1">Adjustment between the competitive strategy and functional supply chain strategies</li><li style="font-weight: 400;" aria-level="1">Proper design of the processes and resources of different functions</li><li style="font-weight: 400;" aria-level="1">Alignment between supply chain design and the role of each stage</li></ol>
A company can fail because of a lack of strategic fit or because the overall design, supply chain processes, and resources do not provide enough to support the desired strategic outcome.

There are three basic steps to achieve this and overcome potential failure:
<ol><li style="font-weight: 400;" aria-level="1">Understand client uncertainty</li><li style="font-weight: 400;" aria-level="1">Understand the supply chain capacities</li><li style="font-weight: 400;" aria-level="1">Implement/Set the strategic fit</li></ol>
In summary, these steps ensure that there is an appropriate supply chain strategy for each product/service. And functional products have an efficient supply chain strategy while innovative products should fit with a responsive supply chain design. This is called the zone of strategic fit.

<img class="size-full wp-image-16270 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc5aa3d157843ae5414_supply-chain-zone-of-strategic-fit.webp" alt="Supply Chain zone of strategic fit" width="558" height="439" />
<h3>Staying competitive</h3>
It is important to note that products have a lifecycle, and the supply chain should account for that. Also, the real world is a dynamic system. That’s why alignment with the business strategy is important. It ensures the correct approach under each state of change.

<img class="size-full wp-image-16268 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc675f55d5da67b5c98_supply-chain-strategy-responsive-vs-efficiency.webp" alt="Supply Chain strategy responsive vs efficiency competitive strategy pyramid" width="903" height="530" />

Being able to understand what the drivers of change are and leverage them is what makes supply chain a field of both science and art. This means your supply chain strategy should leverage the theory, but also be fine-tuned for unique situations.

Therefore, using analytic solutions that can leverage both real data and theory into actionable insights provides huge value for supply chain strategists. Reproducibility is a key factor of success because it enhances visibility and enforces alignment between the scope of strategy and operations, as well as maintains <a href="https://sscs.mit.edu/" target="_blank" rel="noopener">sustainability</a>.

For further studies on the supply chain, audit the free MITx program. 
<h2 id="models">R and Supply Chain Models</h2>
When we’re abstracting a model or testing a specific problem, using spreadsheets seems a great way to get the work done. Because it is at its core, flexible. But, in this situation, it's can be difficult to explain the solution to others and make sure that the appropriate workflow is being followed.

Another drawback of spreadsheets is complex logic. When it comes to more complex problems it becomes harder to set the appropriate logic to design the solution in a steady state. Whereas in R, you can leverage a set of best practices and cutting-edge solutions from packages that are maintained by CRAN. This extends the level of quality that R grants to its users.

Note: CRAN is not without its risks. To ensure your project remains secure, you should explore the <a href="https://appsilon.com/cran-and-the-isoband-incident/" target="_blank" rel="noopener">Isoband Incident and how to mitigate risks</a>.
<h3>SCM in spreadsheets vs R example</h3>
Let’s take a look at an example by comparing the two solutions: spreadsheets vs R.

For each of the metrics in the data, you are asked to calculate the change in the sum of all countries in the ongoing previous month and previous year against the current one:

<img class="size-full wp-image-16254 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc787923e0adc16a0f9_spreadsheet-metric-data-for-r-and-supply-chain-example.webp" alt="SCM spreadsheet vs r example" width="1401" height="560" />

The concept is straightforward, we basically have to:
<ol><li style="font-weight: 400;" aria-level="1">Group the data by date and sum each metric to account for all countries</li><li style="font-weight: 400;" aria-level="1">Calculate the lag from the ongoing previous month and previous year</li><li style="font-weight: 400;" aria-level="1">Calculate the difference between the lagged previous month/year and the current date.</li></ol>
To do this in spreadsheets, there are many approaches you could work on. One such example:

<img class="size-full wp-image-16246 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc8115f687704a610e2_grouping-data-in-spreadsheet.webp" alt="Grouping data in SCM spreadsheet example" width="1600" height="427" />

In this example, we can see that on the 1st of January 2016 56 items were produced while on the 1st of December 2015 it produced 80 items. This is a change in production by -24 items. The same logic applies to the year metric.

The data transformation that was asked for is complete. So what’s the issue then?
<h3>Reproducibility with spreadsheets</h3>
Basically, this approach adds too many manual insertions and each calculation must be checked and updated by the user. There is also the risk of mixing different cells in the calculation, this is the reproducibility problem.

Let’s not forget that we also need 6 other metrics on the data; the same approach is to be repeated 6 times in the spreadsheet.

Imagine for instance that data changes or another metric should be included later on. You will soon enter the spreadsheet productivity dilemma. It was fast to design, became hard to maintain, and now is harder to keep adding features. Soon enough, most of your daily work will revolve around spreadsheet issues instead of focusing on business value.

For the business strategy, this is also a problem. Because it compromises the overall strategy, especially in the supply chain regarding information flow. This issue, therefore, impacts the physical and financial flow. It also makes it harder for businesses to quickly detect changes in the supply chain.

This example is a rather common issue in business. Even beautifully designed dashboards sometimes source an entangled web of spreadsheet data transformations that are connected in non obvious ways and are very hard to understand the data pipeline.
<h3>R solution to the reproducibility problem</h3>
This same problem can be solved in R, in a very elegant solution provided by the tidyverse package:
<pre><code>
cols &lt;- c(
 "produced_items", "orders_count", "revenue",
 "cost", "salvage_value", "profit", "complaints_opened",
 "complaints_closed", "users_active", "users_dropped_out"
)

daily_stats &lt;- dataset_df %&gt;%
 group_by(date) %&gt;%
 summarise(across(all_of(cols), sum, .names = "{col}")) %&gt;%
 mutate(
   across(
     all_of(cols),
     list(
       prev_month = ~ lag(.x, n = 30),
       change_prev_month = ~ .x - lag(.x, n = 30),
       prev_year = ~ lag(.x, n = 365),
       change_prev_year = ~  .x - lag(.x, n = 365)
     ),
   .names = "{col}.{fn}"
   )
 )
</code></pre>
In this example, we can see that all the required steps for this data transformation are kept in the code. This means that understanding and debugging the applications is much easier and faster. And if anything changes in the source, it has a steady-state structure that can be easily updated. 

<img class="size-full wp-image-16262 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cc9970879e28df5f03d_supply-chain-data-view-in-r-output.webp" alt="supply chain data view in r output" width="1591" height="593" />

<img class="size-full wp-image-16260 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01cca3c74b4d4f4d17cc5_supply-chain-data-analysis-output-using-r-daily_stats.webp" alt="supply chain data analysis output using r, daily_stats" width="1101" height="323" />

But R does not only allow you to make reproducible pipelines for dashboards as in the example above. It also allows you to create beautiful dashboards to share this data in a more consumable fashion. With R, you can create a new set of value by designing apps for specific problems - all without needing the skills of a web developer. 

We'll show you how with a solution for the use case scenario below.
<h2 id="usecase">Supply Chain Management in R use case</h2>
Let’s start by presenting a very traditional supply chain design problem as the multiple-commodity transshipment problem.

<img class="size-full wp-image-16250 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01ccb48b83fcd2e540dcc_r-in-supply-chain-design-use-case.webp" alt="R in supply chain design use case - transshipment problem" width="706" height="624" />

In this problem, you minimize the total cost of fulfilling the demand for a set of products at each point of sales, while sharing capacity constraints on plants and distribution centers.

<img class="size-full wp-image-16264 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01ccdc39a0a5ff7bb9a93_supply-chain-design-model.webp" alt="transshipment model" width="544" height="679" />
<h3>Data</h3>
For this problem, we have a template-ready dataset from a spreadsheet, this will have the following structure:
<ol><li style="font-weight: 400;" aria-level="1">Node: Set of each entity of the model with their names</li><li style="font-weight: 400;" aria-level="1">Flow cost: The cost related to sending each product to plant x DC and DC x region</li><li style="font-weight: 400;" aria-level="1">Capacity: The total capacity of the Plants and DCs</li><li style="font-weight: 400;" aria-level="1">Node Arcs: The demand per region/product and capacity of production of each plant/product</li></ol>
<pre><code>
path &lt;- "Transshipment_template.xlsx"

data &lt;- path %&gt;%
 readxl::excel_sheets() %&gt;%
 purrr::set_names() %&gt;%
 purrr::map(readxl::read_excel, path = path)
</code></pre>
To run the model, we must set it to the appropriate structure of R for optimization, this requires a set of data wrangling:
<pre><code>
transship_wrang &lt;- function(data){

 Product &lt;- dplyr::filter(data$Nodes, Entity == "Product")$Name
 Plant &lt;-  dplyr::filter(data$Nodes, Entity == "Plant")$Name
 DC &lt;-  dplyr::filter(data$Nodes, Entity == "DC")$Name
 Region &lt;-  dplyr::filter(data$Nodes, Entity == "Region")$Name

 incost &lt;- dplyr::filter(data$flow_cost, type == "inflow")

 incst &lt;- array(
as.matrix(incost$value),
dim = c(length(Product), length(Plant), length(DC)),
dimnames = list(Product, Plant, DC)
 )

 outcost &lt;- dplyr::filter(data$flow_cost, type == "outflow")

 outcst &lt;- array(
as.matrix(outcost$value),
dim = c(length(Product), length(DC),length(Region)),
dimnames = list(Product, DC, Region)
 )

 PlCapacity &lt;- matrix(
dplyr::filter(data$Capacity, Node == "Plant")$Value,
ncol = 1,
dimnames = list(Plant, "PlCapacity")
 )

 DCCapacity &lt;- matrix(
dplyr::filter(data$Capacity, Node == "DC")$Value,
ncol = 1,
dimnames = list(DC, "DCCapacity")
 )

 PlPrCapacity &lt;- array(
dplyr::filter(data$NodeARCs, Type == "Restriction")$Value,
dim = c(length(Plant),length(Product)),
dimnames = list(Plant, Product)
 )

 Demand &lt;- array(
dplyr::filter(data$NodeARCs, Type == "Demand")$Value,
dim = c(length(Region),length(Product)),
dimnames = list(Region, Product)
 )

 return(
list(
  Product = Product,
  Plant = Plant,
  DC = DC,
  Region = Region,
  incst = incst,
  outcst = outcst,
  PlPrCapacity = PlPrCapacity,
  PlCapacity = PlCapacity,
  DCCapacity = DCCapacity,
  Demand = Demand
)
 )
}

clean_data &lt;- transship_wrang(data)
</code></pre>
<h3>Modeling the transshipment problem in R</h3>
To set this model, we’ll use <a href="https://dirkschumacher.github.io/ompr/index.html" target="_blank" rel="nofollow noopener">ompr</a> since it relates to the mathematical formulation of MILP models, this eases the code x model barrier:
<pre><code>
transship_model &lt;- function(
Product, Plant, DC, Region, incst, outcst,
PlPrCapacity, PlCapacity, DCCapacity, Demand) {

 require(ROI)
 require(ROI.plugin.glpk)

 l &lt;- length(Product) # Number of Products
 i &lt;- length(Plant) #Number of Plants
 k &lt;- length(DC) #Number of transhipments (CDs)
 j &lt;- length(Region) #Number of cities (POS)

model &lt;- ompr::MIPModel() %&gt;%

 # Variable of inflow
 ompr::add_variable(xinf[l,i,k], l = 1:l, i = 1:i, k=1:k, type = "integer", lb = 0) %&gt;%

 # Variable of outflow
 ompr::add_variable(xout[l,k,j], l = 1:l, k = 1:k, j=1:j, type = "integer", lb = 0) %&gt;%

 ompr::set_objective(
ompr::sum_expr(xinf[l,i,k] * incst[l,i,k], l = 1:l, i = 1:i, k=1:k) +  #Inbound Cost
ompr::sum_expr(xout[l,k,j] * outcst[l,k,j], l = 1:l, k = 1:k, j=1:j) #Outbound Cost
 ) %&gt;%
   
   #Plant Production Capacity
ompr::add_constraint(ompr::sum_expr(xinf[l,i,k], k=1:k) &lt;= PlPrCapacity[i,l], l=1:l, i=1:i) %&gt;%

 #Plant Total Capacity
 ompr::add_constraint(ompr::sum_expr(xinf[l,i,k], l=1:l, k=1:k) &lt;= PlCapacity[i], i=1:i) %&gt;%

 #DC Total Capacity
 ompr::add_constraint(ompr::sum_expr(xinf[l,i,k], l=1:l, i=1:i) &lt;= DCCapacity[k], k=1:k) %&gt;%

 #Fulfill Demand
 ompr::add_constraint(ompr::sum_expr(xout[l,k,j], k=1:k) &gt;= Demand[j,l], l=1:l, j=1:j) %&gt;%

 #Flow Constraint
 ompr::add_constraint(
   ompr::sum_expr(xinf[l,i,k], i=1:i) == ompr::sum_expr(xout[l,k,j], j=1:j),
   l=1:l, k=1:k
 )

 #Solve
 result &lt;- ompr::solve_model(model, ompr.roi::with_ROI(solver = "glpk"))

 # Results

 objective &lt;- result$objective_value

Infl &lt;- ompr::get_solution(result, xinf[l,i,k]) %&gt;%
   dplyr::mutate(product = Product[l], source = Plant[i], destiny = DC[k], type = "Inflow") %&gt;%
   dplyr::select(type, product, source, destiny, value)

Outfl &lt;- ompr::get_solution(result, xout[l,k,j]) %&gt;%
 dplyr::mutate(product = Product[l], source = DC[k], destiny = Region[j], type = "Outflow") %&gt;%
  dplyr::select(type, product, source, destiny, value)

 Dcs_Flow &lt;- Infl %&gt;%
dplyr::group_by(destiny, product) %&gt;%
dplyr::summarise(Amount = sum(value)) %&gt;%
as.data.frame()

 Plants_Product &lt;- Infl %&gt;%
dplyr::group_by(source, product) %&gt;%
dplyr::summarise(Amount = sum(value)) %&gt;%
as.data.frame()

 Products_flow &lt;- rbind(Infl, Outfl)

 return(
list(
  objective = objective,
  inflow = Infl,
  outflow = Outfl,
  Products_flow = Products_flow,
  Dcs_Flow = Dcs_Flow,
  Plants_Product = Plants_Product
)
 )
}

model &lt;- transship_model(
 Product = clean_data$Product,
 Plant = clean_data$Plant,
 DC = clean_data$DC,
 Region = clean_data$Region,
 incst = clean_data$incst,
 outcst = clean_data$outcst,
 PlPrCapacity = clean_data$PlPrCapacity,
 PlCapacity = clean_data$PlCapacity,
 DCCapacity = clean_data$DCCapacity,
 Demand = clean_data$Demand
)
</code></pre>
<h3>Results</h3>
<pre><code>
bootstrap &lt;- c("striped", "hover", "responsive") glue::glue("Total Cost: {model$objective}") knitr::kable(model$Plants_Product, caption = "Plants Production") %&gt;%
 kableExtra::kable_styling(bootstrap_options = bootstrap, full_width = F, font_size = 20, position = "float_left")

knitr::kable(model$Dcs_Flow, caption = "DCs Flow") %&gt;%
 kableExtra::kable_styling(bootstrap_options = bootstrap, full_width = F, font_size = 20, position = "right")

knitr::kable(model$inflow, caption = "Inflow") %&gt;%
 kableExtra::kable_styling(bootstrap_options = bootstrap, full_width = F, font_size = 20, position = "float_left")

knitr::kable(model$outflow, caption = "Outflow") %&gt;%
 kableExtra::kable_styling(bootstrap_options = bootstrap, full_width = F, font_size = 20, position = "right")
</code></pre>
Total Cost: 9250

<img class="size-full wp-image-16248 aligncenter" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01ccd115f687704a614fa_modeling-results.webp" alt="R transshipment problem modeling result" width="652" height="523" />
<h2 id="sharing">Sharing SCM results using R Shiny</h2>
You and your team developed a great model and now have valuable insight for the company. How do you share this info with your peers? And can you make this insight interactive, letting them tweak values or set new input data?

You can do this and more by using R Shiny - an interactive web framework for R (and Python).
<blockquote>Are you more of a Python fan? See what's currently possible with our <a href="https://appsilon.com/pyshiny-demo/" target="_blank" rel="noopener">Shiny for Python demo</a>.</blockquote>
Continue below for the full code to build your own Shiny application for your SCM model.
<h3>Aesthetic functions</h3>
<pre><code>
sankey_chart &lt;- function(data, product) { data %&gt;%
   dplyr::filter(product == !!product) %&gt;%
   echarts4r::e_charts() %&gt;%
   echarts4r::e_sankey(source, destiny, value) %&gt;%
   echarts4r::e_title(glue::glue("Product {product} flow")) %&gt;%
   echarts4r::e_tooltip() %&gt;%
   echarts4r::e_theme("dark")
}

reactablefmtr &lt;- function(data, args = TRUE, ...) { data %&gt;%
   dplyr::select(...) %&gt;%
   reactable::reactable(.,
     filterable = args, searchable = args, resizable = args,
     onClick = "select", outlined = TRUE, bordered = TRUE, borderless = TRUE,
     striped = args, highlight = TRUE, compact = args, showSortable = TRUE,
     theme = reactablefmtr::slate()
   )
}
</code></pre>
<h3>Shiny UI</h3>
<pre><code>
ui &lt;- bs4Dash::dashboardPage(
ui &lt;- bs4Dash::dashboardPage(
 title = "Trasshipment Model",
 fullscreen = TRUE,
 dark = T,
 scrollToTop = T,
 header = bs4Dash::dashboardHeader(
   status = "gray-dark",
   title = bs4Dash::dashboardBrand(
     title = "Transshipment Model",
     color = "primary"
   )
 ),
 sidebar = bs4Dash::dashboardSidebar(
   collapsed = T,
   bs4Dash::sidebarMenu(
     bs4Dash::menuItem(
       text = "Transshipment",
       tabName = "transshipment",
       icon = icon("project-diagram")
     )
   )
 ),
 footer = bs4Dash::dashboardFooter(
   right = a(
     href = "https://appsilon.com/",
     "Built with ❤ by Appsilon"
   ),
   left = div(
     icon("calendar"),
     Sys.Date()
   ),
   fixed = T
 ),
 body = bs4Dash::dashboardBody(
   bs4Dash::tabItems(
     bs4Dash::tabItem(
       tabName = "transshipment",
       bs4Dash::tabBox(
         width = 12,
         collapsible = FALSE,
         maximizable = TRUE,
         tabPanel(
           "Model",
           fluidRow(
             column(
               4,
               bs4Dash::box(
                 status = "purple",
                 collapsible = F,
                 width = 12,
                 div(
                   class = "d-flex justify-content-center",
                   a(
                     tags$i(class = "fa fa-database"),
                     href = "www/files/Transshipment_template.xlsx",
                     "Download template",
                     class = "btn btn-default m-1",
                     download = NA, target = "_blank"
                   )
                 ),
                 hr(),
                 fileInput("uploadmodel", "Upload Data"),
                 hr(),
                 div(
                   class = "d-flex justify-content-center",
                   shiny::actionButton(
                     inputId = "model_run",
                     class = "btn btn-success action-button m-1 shiny-bound-input",
                     icon = icon("magic"),
                     label = "Run Model"
                   )
                 )
               )
             ),
             column(
               8,
               bs4Dash::tabBox(
                 width = 12,
                 collapsible = T,
                 maximizable = T,
                 collapsed = F,
                 tabPanel(
                   "Model Info",
                   div(
                     fluidRow(
                       bs4Dash::bs4ValueBoxOutput("products", width = 3),
                       bs4Dash::bs4ValueBoxOutput("plants", width = 3),
                       bs4Dash::bs4ValueBoxOutput("dcs", width = 3),
                       bs4Dash::bs4ValueBoxOutput("regions", width = 3)
                     ),
                     hr(),
                     selectInput(
                       "url_db",
                       label = h5("Choose the data"),
                       choices = c("Nodes", "flow_cost", "Capacity", "NodeARCs")
                     ),
                     shinycssloaders::withSpinner(
                       reactable::reactableOutput("data"),
                       type = 8
                     )
                   )
                 ),
                 tabPanel(
                   "Results",
                   uiOutput("ui_output")
                 )
               )
             )
           )
         )
       )
     )
   )
 )
)
</code></pre>
<h3>Server - Deploying your Supply Chain Management Shiny app</h3>
<pre><code>
server &lt;- function(input, output) {
 data &lt;- reactive({
   path &lt;- input$uploadmodel$datapath path %&gt;%
     readxl::excel_sheets() %&gt;%
     purrr::set_names() %&gt;%
     purrr::map(readxl::read_excel, path = path)
 })

 data_info &lt;- reactive(
   transship_wrang(data())
 )

 output$products &lt;- bs4Dash::renderbs4ValueBox({
   req(input$uploadmodel$datapath)
   bs4Dash::bs4ValueBox(length(data_info()$Product), subtitle = "Products", color = "primary")
 })

 output$plants &lt;- bs4Dash::renderbs4ValueBox({
   req(input$uploadmodel$datapath)
   bs4Dash::bs4ValueBox(length(data_info()$Plant), subtitle = "Plants", color = "primary")
 })

 output$dcs &lt;- bs4Dash::renderbs4ValueBox({
   req(input$uploadmodel$datapath)
   bs4Dash::bs4ValueBox(length(data_info()$DC), subtitle = "DCs", color = "primary")
 })

 output$regions &lt;- bs4Dash::renderbs4ValueBox({
   req(input$uploadmodel$datapath)
   bs4Dash::bs4ValueBox(length(data_info()$Region), subtitle = "Regions", color = "primary")
 })

 output$data &lt;- reactable::renderReactable({
   req(input$uploadmodel$datapath)
   reactablefmtr(data()[input$url_db][[1]], args = FALSE, everything())
 })

 observeEvent(input$model_run, {
   
   if (is.null(input$uploadmodel$datapath)) {
     shinyWidgets::sendSweetAlert(
       title = "Upload a file",
       type = "error",
       text = "Please, Upload a file first"
     )
   } else {  
     model &lt;- transship_model(
         Product = data_info()$Product,
         Plant = data_info()$Plant,
         DC = data_info()$DC,
         Region = data_info()$Region,
         incst = data_info()$incst,
         outcst = data_info()$outcst,
         PlPrCapacity = data_info()$PlPrCapacity,
         PlCapacity = data_info()$PlCapacity,
         DCCapacity = data_info()$DCCapacity,
         Demand = data_info()$Demand
       )
       
     output$total_value &lt;- renderText({
       glue::glue("Total Cost: {model$objective}")
     })
       
     output$sankey_chart &lt;- echarts4r::renderEcharts4r({
       sankey_chart(model$Products_flow, input$product)
     })
       
     output$results_data &lt;- reactable::renderReactable({
       reactablefmtr(model[input$result_data][[1]], args = FALSE, everything())
     })
     
     output$ui_output &lt;- renderUI({

       tagList(
         div(
           class = "d-flex justify-content-center",
           h2(textOutput("total_value"))
         ),
         selectInput(
           "product",
           label = h5("Choose Product"),
           choices = data_info()$Product
         ),
         echarts4r::echarts4rOutput("sankey_chart"),
         selectInput(
           "result_data",
           label = h5("Choose view"),
           choices = c("inflow", "outflow", "Dcs_Flow", "Plants_Product")
         ),
         reactable::reactableOutput("results_data")
       )
     })
   }
 })
}
</code></pre>
<h3>Running the application</h3>
<pre><code>
shinyApp(ui = ui, server = server)
</code></pre>
&nbsp;

<video width="100%" height="auto" src="https://wordpress.appsilon.com/wp-content/uploads/2022/10/supply-chain-management-in-R-shiny-output.mp4" loop="true" autoplay="true" controls="true"></video>


<h2>Summing up R and Shiny in Supply Chain Management</h2>
Supply chain management has many layers of solutions and models designed for each scope of the business strategy. The intrinsic trade-off between those strategies requires visibility, and by being reproducible, R is capable of delivering value to each step in the strategy spectrum.

There are solutions where a spreadsheet definitely shines, especially while designing an idea from scratch. But with R you can extend this to a business-friendly solution in a production-ready state without compromising the flexibility you require for your business life cycle.

There are many other topics in supply chain and applications that can be used with R, but the main insight for this post is that reproducibility is a key factor for success in the alignment between the scope of strategies. This is vital for businesses and makes a significant difference in sustainable and successful solutions. 

And as your project grows, you can <a href="https://appsilon.com/how-we-built-a-shiny-app-for-700-users/" target="_blank" rel="noopener">scale R Shiny</a> and add greater business value using <a href="https://appsilon.com/rstudio-certified-partner/" target="_blank" rel="noopener">enterprise solutions like RStudio products</a>.

Have questions or insights?

Engage with experts, share ideas and take your data journey to the next level!
Explore Possibilities

Share Your Data Goals with Us

From advanced analytics to platform development and pharma consulting, we craft solutions tailored to your needs.

Talk to our Experts
r
shiny dashboard