tylerzika
8/26/2017 - 2:56 AM

Inventory.Elm

module Inventory exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)


-- MODEL


type alias Vendor =
    { name : String
    , email : String
    , items : List VendorItem
    }



-- the target is the number that should always be the onhand inventory in store.
-- the user uses the number input field to send what is on hand, and the target
-- helps determine how much needs to be ordered.
-- example: the target number for Mini 4 1/2 tortilla is 10. If there are 5 onhand, the
-- user puts that in the input and the target in the order becomes 5.


type alias ItemId =
    Int


type alias ItemTarget =
    Int


type alias UpdatedItemTarget =
    Int


type alias VendorItem =
    { id : Int
    , name : String
    , target : Int
    }


initialVendor : Vendor
initialVendor =
    { name = "Diane's"
    , email = "tortillas@dianes.com"
    , items = initialItems
    }


initialItems : List VendorItem
initialItems =
    [ VendorItem 1 "Mini 4 1/2" 10
    , VendorItem 2 "XL Burrito" 9
    , VendorItem 3 "Chip" 5
    , VendorItem 4 "6 Inch Corn" 12
    , VendorItem 5 "Snack Flour" 30
    ]


order : Vendor
order =
    { name = initialVendor.name
    , email = initialVendor.email
    , items = initialItems
    }



-- UPDATE


type Msg
    = UpdateInventory ItemId ItemTarget UpdatedItemTarget


update : Msg -> Vendor -> Vendor
update msg model =
    case msg of
        UpdateInventory value id target ->
            let
                updateOnHand e =
                    --
                    if e.id == id then
                        { e | target = (target - e.target) }
                    else
                        e
            in
                { order | items = List.map updateOnHand order.items }



-- VIEW
-- takes in string, returns a Html msg, which can receive
-- messages from onClick events


appName : String -> Html Msg
appName name =
    Html.h2 [ class "title" ] [ Html.text name ]


viewVendorItem : VendorItem -> Html Msg
viewVendorItem vendorItem =
    li []
        [ text vendorItem.name
        , input [ type_ "number", onInput (UpdateInventory vendorItem.id vendorItem.target) ]
        ]


viewOrderForm : List VendorItem -> Html Msg
viewOrderForm vendorItems =
    vendorItems
        |> List.map viewVendorItem
        |> ul []


view : Vendor -> Html Msg
view vendor =
    div [ class "content" ]
        [ appName "Inventory App"
        , viewOrderForm vendor.items
        , div [ class "button-group" ]
            [ button [] [ text "Order" ] ]
        ]


main : Program Never Vendor Msg
main =
    Html.beginnerProgram
        { model = initialVendor
        , view = view
        , update = update
        }