• 20-06-2024, 13:19:28
    #1
    basit bir magaza yonetim sciptinde satış başarılı olursa alert göstermek istiyorum ama ne yaptıysam gösteremedim. chatgpt falan ugrastım bayaa ama üstesinden gelemedim.

    home.php
    Alıntı
    <?php if(!defined('ADMIN_INCLUDED')) { exit; } ?>
    <?php
        $informations = $db->table('settings')->where('id','=',1)->get();
        if($informations['total_count']=='0')
        {
            m_redirect(ADMIN_URL);
        }
        $info = $informations['data'][0];
    ?>
              <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
              <li class="nav-item" role="presentation">
                <button class="nav-link active" id="pills-home-tab" data-bs-toggle="pill" data-bs-target="#pills-home" type="button" role="tab" aria-controls="pills-home" aria-selected="true">BARKOD TARA</button>
              </li>
              <li class="nav-item" role="presentation">
                <button class="nav-link" id="pills-profile-tab" data-bs-toggle="pill" data-bs-target="#pills-profile" type="button" role="tab" aria-controls="pills-profile" aria-selected="false">MANUEL</button>
              </li>
            </ul>
            <div class="tab-content" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">
              
              
                <div id="reader" width="600px" height="600px"></div>
                <button type="button" class="btn btn-success w-100 sale_barcode_scan"><i class="fa fa-search"></i> BARKOD TARA</button>
              
              </div>
              <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">
              
                <select class="select2 manuel_product " data-placeholder="Ürün arayın">
                <option value="">Ürün Seçiniz</option>
                <?php
                    $products = $db->table('products')->where('status','=','1')->order('name','asc')->get();
                    
                    foreach($products['data'] as $product)
                    {
                        echo '<option value="'.$product['barcode'].'">'.$product['name'].'</option>';
                    }
                ?>
                
                </select>
              
              </div>
            </div>
            
            <form class="sale_form" action="" method="post" enctype="multipart/form-data">
            
            
            <div class="card mt-2 mb-3">
            <div class="card-header fw-bold">ÜRÜNLER</div>
            <div class="card-body">
            
            
            <div class="sale_products">
            
            </div>
            
            </div>
            
            </div>
            
            <div class="card mt-2 mb-3">
            <div class="card-header fw-bold">SATIŞ</div>
            <div class="card-body">
            
            
            <div class="mb-2">
              <label class="form-label fw-bold">Müşteri</label>
              <input type="text" class="form-control" name="customer" required>
            </div>
            
            <div class="mb-2" style="display: none;">
              <label class="form-label fw-bold">İskonto %</label>
              <input type="number" class="form-control" name="discount" value="<?php echo m_setting('discount'); ?>" required>
            </div>
    
    
    <div class="mt-2 mb-2 float-end">
        <b style="font-size:20px;width:100px;display:inline-block;">(USD):</b> 
        <span class="net_total_price" style="font-size:20px">0.00</span> $
        <br>
        <b style="font-size:20px;width:100px;display:inline-block;">(TRY):</b> 
        <span class="total_price_try" style="font-size:20px">0.00</span> ₺
        <br>
        <b style="font-size:20px;width:100px;display:inline-block;">(EUR):</b> 
        <span class="total_price_eur" style="font-size:20px">0.00</span> €
    </div>
    
    <script>
        
        const usdToTryRate = <?php echo $info['usd_try']; ?>;
        const tryToEurRate = <?php echo $info['eur_try']; ?>;
    
        // para birimlerini güncelle
        function updateCurrencyValues() {
            // Net toplam fiyatı (USD) al
            const netTotalPriceUSD = parseFloat(document.querySelector('.net_total_price').innerText);
    
            if (!isNaN(netTotalPriceUSD)) {
                // TRY cinsinden toplam fiyatı hesapla
                const totalPriceTRY = netTotalPriceUSD * usdToTryRate;
                document.querySelector('.total_price_try').innerText = totalPriceTRY.toFixed(2);
    
                // avro hesapla
                const totalPriceEUR = totalPriceTRY / tryToEurRate;
                document.querySelector('.total_price_eur').innerText = totalPriceEUR.toFixed(2);
    
                // Fişi güncelle
                document.querySelector('.print_total_price_try').innerText = totalPriceTRY.toFixed(2);
                document.querySelector('.print_total_price_eur').innerText = totalPriceEUR.toFixed(2);
            }
        }
    
        // net totali güncelle
        const observer = new MutationObserver(updateCurrencyValues);
        observer.observe(document.querySelector('.net_total_price'), { childList: true, subtree: true });
    
        // değerleri güncelle
        updateCurrencyValues();
    </script>
    
    
    
    
    
            
            <button class="btn btn-primary w-100 print_btn mb-2" type="button"><i class="fa fa-print"></i> FİŞ  YAZDIR</button>
            <button class="btn btn-success w-100" type="submit"><i class="fa fa-plus-circle"></i> SATIŞI TAMAMLA</button>
            
            </form>
    
            </div>
    </div>
    
    
    
    <div class="print">
    
    <div class="row mb-5">
    <div class="col-6">
    
    <h1 style="font-size:24px;"><?php echo m_setting('brand'); ?></h1>
    
    </div>
    <div class="col-6 text-start">
    
    <i class="fa fa-map"></i> <?php echo m_setting('address'); ?> <br>
    <i class="fa fa-phone"></i> <?php echo m_setting('phone'); ?> <br>
    <i class="fa fa-envelope"></i> <?php echo m_setting('email'); ?>
    
    </div>
    </div>
    
    <div style="padding-left:5px;" class="mb-2">
    <b>Müşteri:</b> <span class="sale_customer"></span><br><br>
    <b>Tarih:</b> <span class="sale_date"></span>
    </div>
    
    <table class="table">
      <thead>
        <tr>
          <th>Ürün</th>
          <th>Miktar</th>
          <th>Fiyat</th>
          <th>Tutar</th>
        </tr>
      </thead>
      <tbody class="print_products">
        
      </tbody>
    </table>
    
    <div class="mt-2 mb-2 float-end">
            <b style="font-size:20px;width:100px;display:inline-block;">(USD):</b> <span class="net_total_price" style="font-size:20px">0.00</span> $
            <br>
            <b style="font-size:20px;width:100px;display:inline-block;">(TRY):</b> <span class="print_total_price_try" style="font-size:20px">0.00</span> ₺
            <br>
            <b style="font-size:20px;width:100px;display:inline-block;">(EUR):</b> <span class="print_total_price_eur" style="font-size:20px">0.00</span> €
        </div>
    </div>
    
    </div>
    ajax.php
    Alıntı
    <?php
    function removeSizeLabel($data)
    {
        foreach ($data as &$product) {
            $product['variant'] = str_replace('Beden: ', '', $product['variant']);
        }
        return $data;
    }
    
    include('config.php');
    
    if(m_get_session('m_admin')=='' or !m_admin_check())
    {
        $result['status'] = false;
        $result['login'] = true;
        
        echo json_encode($result);
        
        exit;
    }
    
    if($_POST)
    {
        switch(m_u_p('type'))
        {
            case 'barcode_scan':
                $result['status'] = false;
                $result['msg'] = 'Ürün bulunamadı!';
                
                $informations = $db->table('products')->where('barcode','=',m_u_p('barcode'))->where('status','=','1')->get();
                if($informations['total_count']>0)
                {
                    $stock = $db->select('sum(variant_stock) as stock')->table('product_variants')->where('p_id','=',$informations['data'][0]['id'])->get();
                    $stock = $stock['data'][0]['stock'];
                    
                    if($stock=='')
                    {
                        $stock = 0;
                    }
                    
                    if($stock>0)
                    {
                        $result['status'] = true;
                        $result['id'] = $informations['data'][0]['id'];
                        $result['barcode'] = $informations['data'][0]['barcode'];
                        $result['name'] = $informations['data'][0]['name'];
                        $result['image'] = m_image_url($informations['data'][0]['image']);
                    }
                    else
                    {
                        $result['status'] = false;
                        $result['msg'] = 'Ürüne Ait Stok Yok!';
                    }
                }
                else
                {
                    $result['status'] = false;
                    $result['msg'] = 'Ürün bulunamadı!';
                }
                
                echo json_encode($result);
                
                break;
    
            case 'print_forms':
                $saleId = $_POST['saleId'];
                $sale = $db->table('sales')->where('id', '=', $saleId)->get_vars();
                $saleProducts = $db->table('sales_products')->where('s_id', '=', $saleId)->get();
    
                if ($sale && $saleProducts['total_count'] > 0) {
                    $brand = m_setting('brand');
                    $address = m_setting('address');
                    $phone = m_setting('phone');
                    $email = m_setting('email');
    
                    foreach ($saleProducts['data'] as &$product) {
                        $productId = $product['p_id'];
                        $variant = $db->table('product_variants')->where('id', '=', $product['v_id'])->get_vars();
                        $productName = $db->table('products')->where('id', '=', $productId)->get_vars('name');
                        $product['name'] = $productName['name'];
                        $product['variant'] = $variant['variant_type'] . ': ' . $variant['variant_value'];
                    }
    
                    $saleProductsData = removeSizeLabel($saleProducts['data']);
    
                    $response = [
                        'status' => true,
                        'sale' => $sale,
                        'saleProducts' => $saleProductsData,
                        'brand' => $brand,
                        'address' => $address,
                        'phone' => $phone,
                        'email' => $email
                    ];
                } else {
                    $response = [
                        'status' => false,
                        'msg' => 'Satış bulunamadı!'
                    ];
                }
    
                echo json_encode($response);
    
                break;
    
            case 'sale_barcode_scan':
        $result['status'] = false;
        $result['msg'] = 'Ürün bulunamadı!';
        
        $informations = $db->table('products')->where('barcode','=',m_u_p('barcode'))->where('status','=','1')->get();
        if($informations['total_count']>0)
        {
            $info = $informations['data'][0];
            
            // Fiyat çevirme işlemlerini kaldırıyoruz.
            $sale_price = $info['sale_price'];
            
            $rand = uniqid();
            
            $product_variants = $db->table('product_variants')->where('p_id','=',$info['id'])->get();
            
            if($product_variants['total_count']>0)
            {
                $product_variant = '<div><select class="form-select" name="product_variant[]">
                <option value="">Özellik Seçiniz</option>';
                
                foreach($product_variants['data'] as $p_variant)
                {
                    if($p_variant['variant_stock']>0)
                    {
                        $product_variant.= '<option value="'.$p_variant['variant_type'].':'.$p_variant['variant_value'].'">'.$p_variant['variant_type'].':'.$p_variant['variant_value'].'</option>';
                    }
                }
                
                $product_variant.= '</select></div>';
            }
            else
            {
                $product_variant = '<div><select class="form-select" name="product_variant[]">';
                $product_variant.= '<option value="">Özellik Yok</option>';
                $product_variant.= '</select></div>';
            }
            
            $result['status'] = true;
            $result['html'] = '
            <div class="sale_product">
            <input type="hidden" name="product_id[]" value="'.$info['id'].'">
            <input type="hidden" name="product_rand[]" value="'.$rand.'">
            <div class="row">
                <div class="col-lg-4">
                    <div class="mb-1">
                        <label class="form-label fw-bold">Ürün</label>
                        <input type="text" class="form-control" name="product_name[]" value="'.$info['name'].'" readonly>
                    </div>
                </div>
                <div class="col-lg-2">
                    <div class="mb-1">
                        <label class="form-label fw-bold">Özellik</label>
                        '.$product_variant.'
                    </div>
                </div>
                <div class="col-lg-2">
                    <div class="mb-1">
                        <label class="form-label fw-bold">Miktar</label>
                        <input type="number" class="form-control" name="product_quantity[]" value="1">
                    </div>
                </div>
                <div class="col-lg-2">
                    <div class="mb-1">
                        <label class="form-label fw-bold">Fiyat</label>
                        <input type="text" class="form-control product_price" name="product_price[]" value="'.m_currency($sale_price).'">
                    </div>
                </div>
            </div>
            <span class="btn btn-sm btn-danger sale_product_remove w-100"><i class="fa fa-trash"></i></span>    
            </div>';
        }
        else
        {
            $result['status'] = false;
            $result['msg'] = 'Ürün bulunamadı!';
        }
        
        echo json_encode($result);
        
        break;
    
    
           case 'sale_form_calculate':
        $total = 0;
        $net_total = 0;
        $discount = 0;
        
        $products_html = '';
        $n = 0;
        foreach($_POST['product_id'] as $id)
        {
            // Ürün bilgilerini veritabanından çekin
            $product_info = $db->select('name')->table('products')->where('id', '=', $id)->get();
            $product_name = $product_info['data'][0]['name'];
            
            $quantity = $_POST['product_quantity'][$n];
            $variant = $_POST['product_variant'][$n];
            $price = floatval(str_replace(',', '.', $_POST['product_price'][$n]));
            
            $product_total = $price * $quantity;
            
            $variant_info = '';
            
            if ($variant != '') {
                $variant_info = ' ( ' . $variant . ' )';
            }
            
            $products_html .= '<tr><td>' . $product_name . '' . $variant_info . '</td><td>' . $quantity . '</td><td>' . m_currency($price) . '</td><td>' . m_currency($product_total) . '</td></tr>';
            
            $result['products'][] = ['id' => $id, 'total_price' => m_currency($product_total), 'rand' => $_POST['product_rand'][$n]];
            
            $total += $product_total;
            
            $n++;
        }
        
        $discount = m_percent($total, m_u_p('discount'));
        $net_total = $total - $discount;
        $result['discount'] = m_currency($discount);
        $result['total'] = m_currency($total);
        $result['net_total'] = m_currency($net_total);
        $result['products_html'] = $products_html;
        $result['customer'] = m_u_p('customer');
        $result['date'] = date('d/m/Y H:i');
        
        echo json_encode($result);
        break;
    
    
            case 'sale_form':
        if($_POST['product_id'][0]=='')
        {
            $result['status'] = false;
            $result['msg'] = 'Ürün bulunamadı!';
        }
        elseif($_POST['customer']=='')
        {
            $result['status'] = false;
            $result['msg'] = 'Müşteri adını yazınız!';
        }
        else
        {
            $total = 0;
            $net_total = 0;
            $discount = 0;
            
            $products_html = '';
            $n=0;
            foreach($_POST['product_id'] as $id)
            {
                $quantity = $_POST['product_quantity'][$n];
                $variant = $_POST['product_variant'][$n];
                $price = floatval(str_replace(',', '.', $_POST['product_price'][$n]));
                
                $variant_ex = explode(':', $variant);
                
                $stock = $db->select('sum(variant_stock) as stock, id')->table('product_variants')->where('p_id', '=', $id)->where('variant_type', '=', $variant_ex[0])->where('variant_value', '=', $variant_ex[1])->get();
                $stock_id = $stock['data'][0]['id'];
                $stock = $stock['data'][0]['stock'];
                
                if($stock=='')
                {
                    $stock = 0;
                }
                
                if($stock < $quantity)
                {
                    $result['status'] = false;
                    $result['msg'] = ''.$info['name'].' - '.$variant.' için maksimum stok '.$stock.' adettir!';
                    echo json_encode($result);
                    exit;
                }
                
                $product_total = $price * $quantity;
                
                $variant_info = '';
                
                if($variant!='')
                {
                    $variant_info = ' ( '.$variant.' )';
                }
                
                $products_html.= '<tr><td>'.$info['name'].''.$variant_info.'</td><td>'.$quantity.'</td><td>'.m_currency($price).'</td><td>'.m_currency($product_total).'</td></tr>';
                
                $result['products'][] = ['id' => $id, 'variant_id' => $stock_id, 'price' => $price, 'total_price' => $product_total, 'variant' => $variant, 'quantity' => $quantity, 'rand' => $_POST['product_rand'][$n]];
                
                $total = $total + $product_total;
                
                $n++;
            }
            
            $discount = m_percent($total, m_u_p('discount'));
            $net_total = $total - $discount;
            $data = [
                'u_id' => m_admin('id'),
                'customer' => m_u_p('customer'),
                'discount' => m_u_p('discount'),
                'total' => $total,
                'discounted' => $discount,
                'total_price' => $net_total
            ];
            
            $s_id = $db->table('sales')->insert($data);
            
            foreach($result['products'] as $product)
            {
                $data = [
                    's_id' => $s_id,
                    'p_id' => $product['id'],
                    'v_id' => $product['variant_id'],
                    'variant' => $product['variant'],
                    'quantity' => $product['quantity'],
                    'sale_price' => $product['price'],
                    'total_price' => $product['total_price']
                ];
                
                $db->table('sales_products')->insert($data);
                
                $db->query("update product_variants set variant_stock=variant_stock-".$product['quantity']." where id='".$product['variant_id']."'");
            }
            
            $result['status'] = true;
        }
        
        echo json_encode($result);
        
        break;
    
    
            case 'print_form':
                if($_POST['product_id'][0]=='')
                {
                    $result['status'] = false;
                    $result['msg'] = 'Ürün bulunamadı!';
                }
                elseif($_POST['customer']=='')
                {
                    $result['status'] = false;
                    $result['msg'] = 'Müşteri adını yazınız!';
                }
                else
                {
                    $products_html = '';
                    $n=0;
                    foreach($_POST['product_id'] as $id)
                    {
                        $quantity = $_POST['product_quantity'][$n];
                        $variant = $_POST['product_variant'][$n];
                        
                        $variant_ex = explode(':', $variant);
                        
                        $stock = $db->select('sum(variant_stock) as stock, id')->table('product_variants')->where('p_id', '=', $id)->where('variant_type', '=', $variant_ex[0])->where('variant_value', '=', $variant_ex[1])->get();
                        $stock_id = $stock['data'][0]['id'];
                        $stock = $stock['data'][0]['stock'];
                        
                        if($stock=='')
                        {
                            $stock = 0;
                        }
                        
                        if($stock < $quantity)
                        {
                            $result['status'] = false;
                            $result['msg'] = ''.$info['name'].' '.$variant.' için maksimum stok '.$stock.' adettir!';
                            echo json_encode($result);
                            exit;
                        }
                    }
                    
                    $result['status'] = true;
                }
                
                echo json_encode($result);
                
                break;
        }
    }
    ?>

    functions.php
    Alıntı
    <?php
    
    function m_url_get($url,$ref=false)
    {
            if(!$ref)
            {
            $ref = $url;
            }
            $ch = curl_init();
            $timeout = 5;
            curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
            curl_setopt($ch, CURLOPT_REFERER,$ref);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $data= curl_exec($ch);
            curl_close($ch);
            return $data;
    }
    function m_u_p($key)
    {
        return trim(htmlspecialchars(strip_tags(@$_POST[$key])));
    }
    function m_u_g($key)
    {
        return trim(htmlspecialchars(strip_tags(@$_GET[$key])));
    }
    function m_a_p($key)
    {
        return @trim($_POST[$key]);
    }
    function m_a_g($key)
    {
        return @trim($_GET[$key]);
    }
    function m_password($data)
    {
        return md5($data);
    }
    function m_set_session($name,$data)
    {
        $_SESSION[$name] = $data;
    }
    function m_delete_session($name)
    {
        unset($_SESSION[$name]);
        session_destroy();
    }
    function m_get_session($name)
    {
        return @$_SESSION[$name];
    }
    function m_image_url($image,$thumb=false)
    {        
        if($image=='')        
        {        
            $return = UPLOAD_URL.'/images/blank.png';    
        }        
        else    
        {
            if(file_exists(UPLOAD_DIR.'/images/'.$image))
            {
                if($thumb)
                {
                    $return = UPLOAD_URL.'/images/thumb/'.$image;    
                }
                else
                {
                    $return = UPLOAD_URL.'/images/'.$image;    
                }
            }
            else
            {
                $return = UPLOAD_URL.'/images/blank.png';    
            }
        }
        return $return;
    }
    function m_sef($str)
    {
         return URLify::slug($str);
    }
    function m_redirect($url)
    {
        header('Location: '.$url.'');
        exit();
    }
    function m_time_db_format($tarih)
    {
    
        $tarih = date('Y-m-d H:i:s',$tarih);
        return $tarih;
    }
    function m_date_db_format($tarih)
    {
        $tarih = strtotime($tarih);
        $tarih = date('Y-m-d H:i:s',$tarih);
        return $tarih;
    }
    function m_date_to_tr($tarih)
    {
        if($tarih=='')
        {
            return '-';
        }
        else
        {
            return date('d.m.Y H:i',strtotime($tarih));
        }
    }
    function m_date($tarih)
    {
        if($tarih=='')
        {
            return '-';
        }
        else
        {
            return date('d.m.Y',strtotime($tarih));
        }
    }
    function m_date_full_to_tr($tarih)
    {
        if($tarih=='')
        {
            return '-';
        }
        else
        {
            return date('d.m.Y H:i:s',strtotime($tarih));
        }
    }
    function m_time_to_tr($tarih)
    {
        if($tarih=='')
        {
            return '-';
        }
        else
        {
            return date('H:i',strtotime($tarih));
        }
    }
    function m_time_ago($datetime, $full = false) {
        $now = new DateTime;
        $ago = new DateTime($datetime);
        $diff = $now->diff($ago);
    
        $diff->w = floor($diff->d / 7);
        $diff->d -= $diff->w * 7;
    
        $string = array(
            'y' => 'yıl',
            'm' => 'ay',
            'w' => 'hafta',
            'd' => 'gün',
            'h' => 'saat',
            'i' => 'dakika',
            's' => 'saniye',
        );
        foreach ($string as $k => &$v) {
            if ($diff->$k) {
                $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? '' : '');
            } else {
                unset($string[$k]);
            }
        }
    
        if (!$full) $string = array_slice($string, 0, 1);
        return $string ? implode(', ', $string) . ' önce' : 'şimdi';
    }
    function m_time_ago_s($datetime, $full = false) {
        $now = new DateTime;
        $ago = new DateTime($datetime);
        $diff = $now->diff($ago);
    
        $diff->w = floor($diff->d / 7);
        $diff->d -= $diff->w * 7;
    
        $string = array(
            'y' => 'y',
            'm' => 'a',
            'w' => 'h',
            'd' => 'g',
            'h' => 's',
            'i' => 'd',
            's' => 'sn',
        );
        foreach ($string as $k => &$v) {
            if ($diff->$k) {
                $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? '' : '');
            } else {
                unset($string[$k]);
            }
        }
    
        if (!$full) $string = array_slice($string, 0, 1);
        return $string ? implode(',', $string).' önce':'1sn';
    }
    function m_explode($data,$start,$finish,$s,$f)
    {
        $return = explode($start,$data);
        $return = explode($finish,$return[$s]);
        return $return[$f];
    }
    function m_ip()
    {
         if(getenv("HTTP_CLIENT_IP")) {
         $ip = getenv("HTTP_CLIENT_IP");
         } elseif(getenv("HTTP_X_FORWARDED_FOR")) {
         $ip = getenv("HTTP_X_FORWARDED_FOR");
         if (strstr($ip, ',')) {
         $tmp = explode (',', $ip);
         $ip = trim($tmp[0]);
         }
         } else {
         $ip = getenv("REMOTE_ADDR");
         }
         return $ip;
    }
    function m_numbers_only($_input) 
    { 
        return floatval($_input); 
    }
    function m_currency($number)
    {
        if($number=='')
        {
            $number = '0.00';
        }
        else
        {
        $number = number_format($number,2,',','.');
        }
        return $number;
    }
    
    function m_r_time($bitmesi_gereken)
    {
        
        $tarih1 = new DateTime(date('Y-m-d H:i:s'));
        $tarih2 = new DateTime($bitmesi_gereken);
        $interval = $tarih1->diff($tarih2);
        $fark_gun = $interval->format("%d");
        $fark_saat = $interval->format("%h");
        $fark_dakika = $interval->format("%i");
        if(time()>strtotime($bitmesi_gereken))
        {
            return '0 Dakika';
        }
        else
        {
            return ''.$fark_saat.' Saat '.$fark_dakika.' Dakika';
        }
    }
    
    
    function strip_tags_content($text, $tags = '', $invert = FALSE) 
    {
    
      preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
      $tags = array_unique($tags[1]);
       
      if(is_array($tags) AND count($tags) > 0) {
        if($invert == FALSE) {
          return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
        }
        else {
          return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
        }
      }
      elseif($invert == FALSE) {
        return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
      }
      return $text;
    }
    
    function entities( $string ) 
    {
        $stringBuilder = "";
        $offset = 0;
    
        if ( empty( $string ) ) {
            return "";
        }
    
        while ( $offset >= 0 ) {
            $decValue = ordutf8( $string, $offset );
            $char = unichr($decValue);
    
            $htmlEntited = htmlentities( $char );
            if( $char != $htmlEntited ){
                $stringBuilder .= $htmlEntited;
            } elseif( $decValue >= 128 ){
                $stringBuilder .= "&#" . $decValue . ";";
            } else {
                $stringBuilder .= $char;
            }
        }
    
        return $stringBuilder;
    }
    function ordutf8($string, &$offset) 
    {
        $code = ord(substr($string, $offset,1));
        if ($code >= 128) {        //otherwise 0xxxxxxx
            if ($code < 224) $bytesnumber = 2;                //110xxxxx
            else if ($code < 240) $bytesnumber = 3;        //1110xxxx
            else if ($code < 248) $bytesnumber = 4;    //11110xxx
            $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
            for ($i = 2; $i <= $bytesnumber; $i++) {
                $offset ++;
                $code2 = ord(substr($string, $offset, 1)) - 128;        //10xxxxxx
                $codetemp = $codetemp*64 + $code2;
            }
            $code = $codetemp;
        }
        $offset += 1;
        if ($offset >= strlen($string)) $offset = -1;
        return $code;
    }
    function unichr($u) {
        return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
    }
    
    
    function m_alert($title,$data)
    {
        switch($title)
        {
            case 'Hata':
            $type = 'danger';
            $icon = 'fa-exclamation-triangle';
            break;
            case 'Bilgi':
            $type = 'info';
            $icon = 'fa-info';
            break;
            case 'Başarılı':
            $type = 'success';
            $icon = 'fa-check';
            break;
            default;
            $type = "info";
        }
        return '<div class="alert alert-'.$type.'"  style="word-break: break-word;"> <i class="fa '.$icon.'"></i> 
      '.$title.' - '.$data.'
    </div>';
    }
    function m_status($data)
    {
        if($data==0)
        {
            return '<span class="badge bg-warning">Pasif</span>';
        }
        if($data==1)
        {
            return '<span class="badge bg-success">Aktif</span>';
        }
        
    }
    
    function m_setting($data)
    {
        $db = new DB();
        
        $return = $db->table('settings')->where('id','=','1')->get_var($data);
        
        return $return;
    }
    
    
    
    function m_authority($authoritys,$authority)
    {
    
        $authority_check = m_explode($authoritys,'<'.$authority.'>','</'.$authority.'>',1,0);
        if($authority_check=='1')
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    
    function variant_types()
    {
        $list = array('Beden','Renk','Numara','Gram','Kilo','Ağırlık','Uzunluk','Genişlik','Metre');
        
        return $list;
    }
    
    function price_types()
    {
        $list = array('TL','$','€');
        
        return $list;
    }
    
    
    function m_percent($number,$percent){ 
        return ($number*$percent)/100;
    }
    
    ?>
    theme.js
    Alıntı
    function printSale(saleId) {
        // AJAX isteği yaparak ilgili satış bilgilerini alın
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: { type: "print_forms", saleId: saleId },
            dataType: "json",
            success: function (response) {
                if (response.status) {
                    // Satış bilgileri başarılı bir şekilde alındı
                    var sale = response.sale;
                    var saleProducts = response.saleProducts;
    
                    // Yazdırma işlemi için bir pop-up penceresi oluşturun
                    var printWindow = window.open('', '_blank');
    
                    // Yazdırma işlemi için pop-up penceresinin içeriğini oluşturun
                    printWindow.document.open();
                    printWindow.document.write('<html><head><title>Satış Raporu</title>');
                    printWindow.document.write('<link rel="stylesheet" type="text/css" href="yazdir3.css">');
                    printWindow.document.write('<link rel="stylesheet" type="text/css" href="assets/fontawesome/css/all.min.css">');
                    
                    printWindow.document.write('</head><body>');
    
                    // Satış raporu içeriğini oluşturun
                    printWindow.document.write('<div class="print">');
    
                    printWindow.document.write('<div class="row mb-5">');
                    printWindow.document.write('<div class="col-6">');
                    
                    printWindow.document.write('<img src="qr.png" alt="QR Code" class="qr-code">');
                    printWindow.document.write('<h1 style="font-size:24px;">' + response.brand + '</h1>');
                    printWindow.document.write('</div>');
                    printWindow.document.write('<div class="col-6 text-start">');
                    printWindow.document.write('<i class="fa fa-map"></i> ' + response.address + '<br>');
                    printWindow.document.write('<i class="fa fa-phone"></i> ' + response.phone + '<br>');
                    printWindow.document.write('<i class="fa fa-envelope"></i> ' + response.email);
                    printWindow.document.write('</div>');
                    printWindow.document.write('</div>');
    
                    printWindow.document.write('<div style="padding-left:5px;" class="mb-2">');
                    printWindow.document.write('<b>Customer:</b> <span class="sale_customer style="font-size:20px">' + sale.customer + '</span><br><br>');
                    printWindow.document.write('<b>DATE:</b> <span class="sale_date">' + sale.date + '</span>');
                    printWindow.document.write('</div>');
    
                    printWindow.document.write('<table class="table">');
                    printWindow.document.write('<thead><tr><th>Product</th><th>Quantity</th><th>Price</th><th>Amount</th></tr></thead>');
                    printWindow.document.write('<tbody class="print_products">');
                    for (var i = 0; i < saleProducts.length; i++) {
                        var product = saleProducts[i];
                        printWindow.document.write('<tr>');
                        printWindow.document.write('<td>' + product.name + ' (' + product.variant + ')' + '</td>');
                        printWindow.document.write('<td>' + product.quantity + '</td>');
                        printWindow.document.write('<td>' + product.sale_price + '</td>');
                        printWindow.document.write('<td>' + product.total_price + '</td>');
                        printWindow.document.write('</tr>');
                    }
                    printWindow.document.write('</tbody>');
                    printWindow.document.write('</table>');
    
                    printWindow.document.write('<div class="mt-2 mb-2 float-end">');
                    printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Amount:</b> <span class="total_price" style="font-size:20px">' + sale.total + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                    printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Discount:</b> <span class="total_discount" style="font-size:20px">' + sale.discounted + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                    printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Total:</b> <span class="net_total_price" style="font-size:20px">' + sale.total_price + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                    printWindow.document.write('</div>');
    
                    
    
                    printWindow.document.write('</div>'); // .print
    
                    printWindow.document.write('</body></html>');
                    printWindow.document.close();
    
                    // CSS dosyasının yüklenmesini bekleyin ve yazdırma işlemini başlatın
                    printWindow.onload = function () {
                        printWindow.print();
                    };
                } else {
                    // Hata durumunda gerekli işlemleri burada yapabilirsiniz
                    console.error(response.msg);
                }
            },
            error: function (xhr, status, error) {
                // AJAX hatası durumunda gerekli işlemleri burada yapabilirsiniz
                console.error(error);
            }
        });
    }
    
    
    
    
    function sale_calculate()
    {
        var form_data = $('.sale_form').serialize();
        
         $.ajax({
            type: 'POST',
            url: ajax_url,
            data: 'type=sale_form_calculate&'+form_data+'',
            dataType: 'json',
            success: function(data)
            {
                $.each(data.products, function(k, product) {
                    
                      $('.product_total_'+product.rand+'').val(product.total_price);
                });
                
                $('.total_price').html(data.total);
                $('.net_total_price').html(data.net_total);
                $('.total_discount').html(data.discount);
                $('.print_products').html(data.products_html);
                $('.sale_date').html(data.date);
                $('.sale_customer').html(data.customer);
                
            }
        });
    }
    
    $(document).ready(function() 
    {
        
        $( '.select2' ).select2( {
            width: '100%',
            placeholder: $( this ).data( 'placeholder' ),
        } );
        
        
       $('.sale_form').on('change keyup paste', ':input', function(e) {
            
            
            sale_calculate();
            
       });
        var $_GET = {};
        
        document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
        function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
        }
    
            $_GET[decode(arguments[1])] = decode(arguments[2]);
        });
        if($_GET["date"])
        {
    
            var tarihler = $_GET["date"].split(" - ");
            var st = tarihler[0];
            var ed = tarihler[1];
        }
        else
        {
            var st = "01.01.2023";
            var ed = "01.01.2024";
        }
    
        $('.daterange-ranges').daterangepicker(
                {
                    showCustomRangeLabel:false,
                    startDate:st,
                    endDate:ed,
                    minDate: '01.01.2023',
                    maxDate: '30.12.2025',
                    dateLimit: { days: 60 },
                    autoApply: true,
                    ranges: {
                      'Bugün': [moment(), moment()],
                        'Dün': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Son 1 Hafta': [moment().subtract(6, 'days'), moment()],
                        'Son 1 Ay': [moment().subtract(29, 'days'), moment()],
                        'Bu Ay': [moment().startOf('month'), moment().endOf('month')],
                        'Geçen Ay': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    opens: 'right',
                    applyClass: 'btn-sm bg-slate-600',
                    cancelClass: 'btn-sm btn-light',
                    locale: {
                    format: 'DD.MM.YYYY',
                    applyLabel: 'Uygula',
                    cancelLabel: 'Kapat',
                    startLabel: 'Başlangıç',
                    endLabel: 'Bitiş',
                    daysOfWeek: ['Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cm','Cmts'],
                    monthNames: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']
                    }
                },
                function(start, end) {
                    $('.daterange-ranges span').html(start.format('DD.MM.YYYY') + ' - ' + end.format('DD.MM.YYYY'));
                }
            );
    
           
           
        if ($('.datatable').length)
        {
            
            var table = $(".datatable").DataTable({
            dom: "<'datatable_header'<l><B><f>><'row'<'col-sm-12'tr>><'datatable_footer'<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>>",
            charset: "UTF-8",
              buttons: {            
                    buttons: [
                        {
                            extend: 'colvis',
                            className: 'btn btn-light',
                            text: '<i class="fas fa-th-list"></i> Görünüm'
                        },
                        {
                            extend: 'copy',
                            className: 'btn btn-light',
                            text: '<i class="fa fa-copy"></i> Kopyala'
                        },
                        {
                            extend: 'excel',
                            className: 'btn btn-light',
                            text: '<i class="fas fa-table"></i> Excel'
                        },
                        {
                        extend: 'print',
                         customize: function ( win ) {
                        $(win.document.body)
                            .css( 'font-size', '10pt' );
     
                        $(win.document.body).find( 'table' )
                            .addClass( 'compact' )
                            .css( 'font-size', 'inherit' );
                        },
                        text: '<i class="fa fa-print"></i> Yazdır',
                        className: 'btn btn-light',
                        exportOptions: {
                            columns: ':visible'
                        }
                        }
                    ]
                },
                
                aaSorting:[],
                language:
                {
                    "sDecimal":        ",",
                    "sEmptyTable":     "Tabloda herhangi bir veri mevcut değil",
                    "sInfo":           "_TOTAL_ kayıttan _START_ - _END_ arasındaki kayıtlar gösteriliyor",
                    "sInfoEmpty":      "Kayıt yok",
                    "sInfoFiltered":   "(_MAX_ kayıt içerisinden bulunan)",
                    "sInfoPostFix":    "",
                    "sInfoThousands":  ".",
                    "sLengthMenu":     "_MENU_ Görüntüle",
                    "sLoadingRecords": "Yükleniyor...",
                    "searchPlaceholder": "Arama...",
                    "sProcessing":     "İşleniyor...",
                    "sSearch":         "",
                    "sZeroRecords":    "Eşleşen kayıt bulunamadı",
                    "oPaginate": {
                        "sFirst":    "İlk",
                        "sLast":     "Son",
                        "sNext":     "Sonraki",
                        "sPrevious": "Önceki"
                    },
                    "oAria": {
                        "sSortAscending":  ": artan sütun sıralamasını aktifleştir",
                        "sSortDescending": ": azalan sütun sıralamasını aktifleştir"
                    },
                    "select": {
                        "rows": {
                            "_": "%d kayıt seçildi",
                            "0": "",
                            "1": "1 kayıt seçildi"
                        }
                    },
                    buttons: {
                            copyTitle: 'Kopyalama İşlemi',
                            copySuccess: {
                                1: "Satırlar kopyalandı.",
                                _: "%d satır kopyalandı."
                            }
                        }
                }
            }).buttons().container().appendTo(".dataTables_wrapper .col-md-6:eq(0)");
            
            $(".dataTables_length select").addClass("form-select form-select-sm");
            
            $("div.dataTables_filter input").focus();
          
        }
        
    });
    
    $(document).on('click', '.delete', function (e) {
        
       e.preventDefault();
       var url = $(this).attr('href');
       
       Swal.fire({
          icon:"question",
          customClass: {
            confirmButton: 'btn btn-danger me-2',
            cancelButton: 'btn btn-success me-2'
          },
          buttonsStyling: false,
          html: 'Bu içeriği silmek istediğinizden  eminmisiniz ?',
          showCancelButton: true,
          confirmButtonText: 'Evet',
          cancelButtonText: 'Hayır',
        }).then((result) => {
          if (result.isConfirmed) {
            
            window.location.href=url;
            
          }
        });
       
              
    
        
    });
    
    $(document).on('click', '.add_variant', function (e) {
        
       e.preventDefault();
       var clone = $('.product_variant_clone').html();
       
       $('.product_variants').append('<div class="product_variant">'+clone+'</div>');
       
       
              
    
        
    });
    
    $(document).on('click', '.variant_remove', function (e) {
        
       e.preventDefault();
       $(this).closest('.product_variant').remove();
       
       
              
    
        
    });
    
    
    
    
    
    
    
    $(document).on('click', '.sale_product_remove', function (e) {
        
       $(this).closest('.sale_product').remove();
       
       sale_calculate();
    
    
        
    });
    
    
    $(document).on('submit', '.sale_form', function (e) {
        
       e.preventDefault();
       
       
       var form_data = $('.sale_form').serialize();
        
         $.ajax({
            type: 'POST',
            url: ajax_url,
            data: 'type=sale_form&'+form_data+'',
            dataType: 'json',
            success: function(data)
            {
                if(data.status)
                {
                        
                    window.location.reload();
                    
                }
                else
                {
                        Swal.fire({
                          icon: 'error',
                          title: 'Hata',
                          text: data.msg,
                          confirmButtonText: 'Tamam'
                        });
                }
            }
        });
       
        
    
    
        
    });
    
    function barcode_scanner(barcode)
    {
        html5QrCode.stop();
         $.ajax({
            type: 'POST',
            url: ajax_url,
            data: 'type=barcode_scan&barcode='+barcode+'',
            dataType: 'json',
            success: function(data)
            {
                
                if(data.status)
                {
                    $('.product_name').val(data.name);
                    $('.product_id').val(data.id);
                    $('.product_image_url').attr('href',data.image);
                    $('.product_image_src').attr('src',data.image);
                }
                else
                {
                    if(data.login)
                    {
                        window.location.href = login_url;
                    }
                    else
                    {
                        Swal.fire({
                          icon: 'error',
                          title: 'Hata',
                          text: data.msg,
                          confirmButtonText: 'Tamam'
                        });
                    }
                }
                
            }
        });
    }
    
    function sale_barcode_scanner(barcode,stat=true)
    {
        if(stat)
        {
            html5QrCode.stop();
        }
        
        $.ajax({
            type: 'POST',
            url: ajax_url,
            data: 'type=sale_barcode_scan&barcode='+barcode+'',
            dataType: 'json',
            success: function(data)
            {
                
                if(data.status)
                {
                    $('.sale_products').prepend(data.html);
                    
                    sale_calculate();
                }
                else
                {
                    if(data.login)
                    {
                        window.location.href = login_url;
                    }
                    else
                    {
                        Swal.fire({
                          icon: 'error',
                          title: 'Hata',
                          text: data.msg,
                          confirmButtonText: 'Tamam'
                        });
                    }
                }
                
            }
        });
    }
    
    function product_barcode_scanner(barcode)
    {
        html5QrCode.stop();
        
        $('.pr_barcode').val(barcode);
    }
    
    const html5QrCode = new Html5Qrcode("reader");
    const qrCodeSuccessCallback = (decodedText, decodedResult) => {
        
        barcode_scanner(decodedText);
        
        html5QrCode.stop();
        
    };
    const config = { fps: 10, qrbox: { width: 250, height: 250 } };
    
    $(document).on('click', '.barcode_scan', function (e) {
        
        
       
        html5QrCode.start({ facingMode: "environment" }, config, barcode_scan);
    
    
        
    });
    
    $(document).on('click', '.sale_barcode_scan', function (e) {
        
        
       
        html5QrCode.start({ facingMode: "environment" }, config, sale_barcode_scanner);
    
    
        
    });
    
    $(document).on('click', '.product_barcode_scan', function (e) {
        
        
       
        html5QrCode.start({ facingMode: "environment" }, config, product_barcode_scanner);
    
    
        
    });
    
    
    $(document).on('change', '.manuel_product', function (e) {
        
           sale_barcode_scanner($(this).val(),false);  
    
        
    });
    
    
    $(document).on('click', '.print_btn', function (e) {
        
       e.preventDefault();
       
       
       var form_data = $('.sale_form').serialize();
        
         $.ajax({
            type: 'POST',
            url: ajax_url,
            data: 'type=print_form&'+form_data+'',
            dataType: 'json',
            success: function(data)
            {
                if(data.status)
                {
                        
                    $('.print').print({
                        globalStyles : true,
                        mediaPrint : true,
                        iframe : false
                    });
                    
                }
                else
                {
                        Swal.fire({
                          icon: 'error',
                          title: 'Hata',
                          text: data.msg,
                          confirmButtonText: 'Tamam'
                        });
                }
            }
        });
       
        
    
    
        
    });
    Satış tamamla dediğimde sorunsuz bir şekilde satış oluşturuluyor ve dbye kaydediliyor. sales_reports sayfasında görünüyor. ama herhangi bir alert div yada herhangi bir gösteremiyorum satışın başarılı olduguyla ilgili
  • 20-06-2024, 13:51:31
    #2
    ücretli destek sağlarım .
  • 20-06-2024, 14:01:01
    #3
    Alert için sweatalert tarzı bir kütüphane kullanın işiniz daha kolay olacaktır. Ajax işleminde response değerini kontrol edin. True veya false harici bir değer mi dönüyor inceleyin. Eğer bir problem yoksa yazdırılan html bloklarında problem vardır. Consoledan takip edersiniz.
  • 20-06-2024, 14:05:06
    #4
    ajax.php 66 dan sonra

    $response = [];
    Anladığım kadarıyla değişkeni if/else içerisinde oluşturup dışında bastırmaya çalışıyorsun. Değişkene ulaşamadığı için değer basamıyor.
  • 20-06-2024, 14:37:21
    #5
    OguzhanLevent adlı üyeden alıntı: mesajı görüntüle
    ajax.php 66 dan sonra

    $response = [];
    Anladığım kadarıyla değişkeni if/else içerisinde oluşturup dışında bastırmaya çalışıyorsun. Değişkene ulaşamadığı için değer basamıyor.
    Hocam gün içinde müsaitliğiniz olursa anydesk ile bağlanma şansınız olur mu?
  • 20-06-2024, 14:38:52
    #6
    YaLaN adlı üyeden alıntı: mesajı görüntüle
    Hocam gün içinde müsaitliğiniz olursa anydesk ile bağlanma şansınız olur mu?
    Telefon numaramı pm olarak atıyorum hocam akşam eve geçtiğimde bağlanıp bakayım
  • 20-06-2024, 15:06:33
    #7
    olay ajax ile gerçekleşip js tarafında kullanıcıya gösteriliyor.

    yapmanız gereken en basit haliyle js tarafındaki kodu aşağıdaki gibi düzeltmek

    $(document).on('submit', '.sale_form', function (e) {     
       e.preventDefault();
       var form_data = $('.sale_form').serialize();
      $.ajax({
        type: 'POST',
        url: ajax_url,
        data: 'type=sale_form&' + form_data,
        dataType: 'json',
        success: function(data) {
            if (data.status) {
                Swal.fire({
                  icon: 'success',
                  title: 'Sonuç',
                  text: 'Siparişiniz başarıyla verilmiştir. Teşekkür ederiz.',
                  confirmButtonText: 'Tamam'
                }).then((result) => {
                  window.location.reload();
                });
            } else {
              Swal.fire({
                icon: 'error',
                title: 'Hata',
                text: data.msg,
                confirmButtonText: 'Tamam'
              });
            }
        }
    });