Ir para conteúdo
Fórum Script Brasil

Todas Atividades

Atualizada automaticamente

  1. Recentemente
  2. Yesterday
  3. Bom dia pessoal! Estou com uma tremenda dúvida e com um constante problema em uma planilha, preciso formatar todas as caixas de textos que possuírem "Money" na região Tag! Mas eu já estou a alguns dias tentando mesclar os dois módulos de classe e não consigo, um sempre conflita com o outro. Vou lhes enviar 'User Form Private CollecaoTextBoxes As Collection Private Sub TxtValor_Change() If Len(Me.TxtValor.value) = 0 Then Me.LblValor.Caption = "Valor" Me.LblValor.Top = 98 Me.LblValor.ForeColor = RGB(116, 116, 116) Else Me.LblValor.Caption = "Valor" Me.LblValor.Top = 80 Me.LblValor.ForeColor = RGB(47, 62, 255) End If End Sub Private Sub TxtPgt_Change() If Len(Me.TxtPgt.value) = 0 Then Me.LblPgt.Caption = "Prazos" Me.LblPgt.Top = 98 Me.LblPgt.ForeColor = RGB(116, 116, 116) Else Me.LblPgt.Caption = "Prazos" Me.LblPgt.Top = 80 Me.LblPgt.ForeColor = RGB(47, 62, 255) End If End Sub ' Módulo de Formulário Private Sub UserForm_Initialize() InitializeTextBoxes Me Set CollecaoTextBoxes = New Collection Dim ctrl As Control Dim validador As ValidadorTextBox For Each ctrl In Me.Controls If TypeName(ctrl) = "TextBox" Then Set validador = New ValidadorTextBox validador.Initialize ctrl CollecaoTextBoxes.Add validador End If Next ctrl End Sub 'Módulo Comum Módulo 1 Option Explicit Private colTextBoxes As Collection Public Sub InitializeTextBoxes(ByVal frm As Object) Dim ctrl As Control Set colTextBoxes = New Collection ' Loop através de todos os controles no formulário For Each ctrl In frm.Controls If TypeName(ctrl) = "TextBox" Then ' Instancia o módulo de classe para cada TextBox Dim clsTextBox As TextBoxMoney Set clsTextBox = New TextBoxMoney Set clsTextBox.TextBox = ctrl colTextBoxes.Add clsTextBox End If Next ctrl End Sub ' Módulo de classe TextBoxMoney Option Explicit Private WithEvents txtBox As MSForms.TextBox Private commaAllowed As Boolean Public decimalSeparator As String Private Sub txtBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) decimalSeparator = Application.International(xlDecimalSeparator) If InStr(1, txtBox.Tag, "Teste", vbTextCompare) > 0 Then If Not (IsNumeric(Chr(KeyAscii)) Or KeyAscii = 44 Or KeyAscii = 8 And Chr(KeyAscii) <> decimalSeparator) Then ' Permite apenas números e a vírgula KeyAscii = 0 ElseIf KeyAscii = 44 Then ' Verifica se é uma vírgula If Not commaAllowed Then ' Permite apenas uma vírgula e apenas se não houver outra vírgula já inserida KeyAscii = 0 Else commaAllowed = False ' Desabilita a inserção de mais vírgulas End If ElseIf KeyAscii = 8 Then ' Verifica se é o caractere backspace If Right(txtBox.text, 1) = "," Then ' Permite a exclusão de caracteres commaAllowed = True ' Permite a inclusão de uma nova vírgula se a última entrada for uma vírgula End If ElseIf InStr(txtBox.text, ",") > 0 Then Dim afterComma As String ' Verifica se há uma vírgula na string afterComma = Split(txtBox.text, ",")(1) If Len(afterComma) >= 2 Then ' Limita a inserção de caracteres após a vírgula a dois dígitos KeyAscii = 0 End If Else ' Permitir a adição de uma nova vírgula se não houver vírgula na string commaAllowed = True End If End If End Sub Public Property Set TextBox(ByVal txt As MSForms.TextBox) Set txtBox = txt End Property 'Módulo de Classe ValidadorTextBox Option Explicit Private commaAllowed As Boolean Private WithEvents txtBox As MSForms.TextBox Private decimalSeparator As String Public Sub Initialize(txt As MSForms.TextBox) Set txtBox = txt ' Define o separador decimal com base nas configurações regionais decimalSeparator = Application.International(xlDecimalSeparator) End Sub Private Sub txtBox_Change() If txtBox.Tag = "Money" Then Dim valor As String Dim parteInteira As String Dim parteDecimal As String Dim ponto As Long valor = txtBox.text ' Verifica se o valor começa com "R$ " If Left(valor, 3) = "R$ " Then ' Remove o prefixo "R$ " valor = Mid(valor, 4) End If ' Remove o separador de milhares atual, se houver valor = Replace(valor, ".", "") ' Verifica se o separador decimal é uma vírgula (configuração regional) If decimalSeparator = "," Then ' Substitui vírgulas por pontos para garantir a uniformidade valor = Replace(valor, ",", ".") End If ' Divide o valor em parte inteira e parte decimal ponto = InStr(valor, ".") If ponto > 0 Then parteInteira = Left(valor, ponto - 1) parteDecimal = Mid(valor, ponto + 1) Else parteInteira = valor parteDecimal = "" End If ' Adiciona pontos de demarcação para milhares parteInteira = Format(parteInteira, "#,##0") ' Reconstroi o valor completo valor = parteInteira If Len(parteDecimal) > 0 Then valor = valor & decimalSeparator & parteDecimal End If ' Verifica se o valor numérico foi removido If valor = "" Then ' Remove o prefixo "R$ " se o valor for vazio txtBox.text = "" Else ' Adiciona o prefixo "R$ " valor = "R$ " & valor ' Atualiza o valor na caixa de texto txtBox.text = valor End If ' Move o cursor para o final do texto txtBox.SelStart = Len(txtBox.text) End If End Sub Public Property Set TextBox(ByVal txt As MSForms.TextBox) Set txtBox = txt End Property
  4. An email warm-up tool can be a game-changer for cold email campaigns. Let's explore how it can address the challenges mentioned above: Improved Email Deliverability Boost Inbox email warm-up tools help improve email deliverability by up to 80% by gradually increasing the volume of emails sent from a new email address. This reduces the risk of being flagged as spam. Increased Open Rates By ensuring that emails land directly in the primary inbox instead of the spam folder, an email warm-up tool can increase open rates significantly. Enhanced Email Reputation Boost Inbox helps build a positive email reputation by establishing a history of engagement with the recipient's email server, making future emails more likely to be delivered. Spam Filter Avoidance Boost Inbox helps you avoid spam filters by optimizing your email content and ensuring it meets all spam filter criteria. Your emails are more likely to land in the primary inbox. Detailed Analytics Track the performance of your email reputation with detailed analytics provided by Boost Inbox. Know how many emails are opened, what your spam score is, and what your bounce rate is.
  5. In the fast-paced world of digital content creation, one question continues to linger: How long should a blog post be? With the ever-changing landscape of online consumption and search engine algorithms, determining the ideal length for a blog post can be challenging. However, by understanding the factors that influence post length and the varying needs of different types of content, bloggers can navigate this question with confidence. Is There an Ideal Blog Post Length? The quest for the perfect blog post length has been a topic of debate among content creators for years. Some argue that shorter posts are more engaging and easier for readers to digest, while others advocate for longer, more in-depth content that provides comprehensive information. The truth is, there is no one-size-fits-all answer to this question. The ideal length of a blog post depends on a variety of factors, including the topic, the target audience, and the goals of the content creator. The Optimal Blog Post Length Depends on These Factors Topic Complexity: Complex topics often require more space to fully explore and explain. In these cases, longer blog posts may be necessary to provide readers with a thorough understanding of the subject matter. Audience Preferences: Understanding the preferences of your target audience is key to determining the optimal length for your blog posts. Some audiences may prefer shorter, more concise content, while others may appreciate longer, more detailed articles. Search Engine Optimization (SEO) Considerations: Search engines like Google tend to favor longer-form content, as it typically provides more value to readers. Longer blog posts also tend to rank higher in search engine results pages (SERPs), driving more organic traffic to your site. Content Goals: Consider the goals of your blog post when determining its length. Are you looking to inform, entertain, persuade, or inspire your readers? The length of your post should align with its intended purpose. Ideal Number of Words Per Type of Content While there is no definitive answer to the question of blog post length, there are some general guidelines that can help content creators determine the ideal word count for their posts. Here's a breakdown of recommended word counts for different types of content:. 500-Word Blog Posts: Short, concise blog posts are perfect for addressing simple topics or providing quick tips and tricks to readers. These posts are easy to digest and are often well-suited for audiences with short attention spans. 1000-Word Blog Posts: Medium-length blog posts allow for more in-depth exploration of a topic without overwhelming readers. They provide enough space to cover multiple subtopics or to delve deeper into a single subject. 2000-Word Blog Posts: The Benefits of Writing Long-Form Posts: Long-form blog posts offer the opportunity to thoroughly examine complex topics and provide readers with comprehensive information. These posts tend to perform well in search engine rankings and are highly shareable on social media. How to Determine Your Blog Post Length in 6 Steps? Identify Your Audience: Get to know your target audience and understand their preferences, interests, and needs. Define Your Goals: Clearly define the goals of your blog post. Are you looking to educate, entertain, inspire, or persuade your readers? Choose Your Topic: Select a topic that aligns with the interests and needs of your target audience. Conduct Research: Conduct thorough research on your chosen topic to gather enough information to support your blog post. Outline Your Content: Create an outline for your blog post to organize your thoughts and ensure that you cover all relevant points. Write and Edit: Write your blog post, keeping your audience, goals, and topic in mind. Edit your content to ensure clarity, coherence, and conciseness. Long-form Posts and SEO In recent years, long-form content has become increasingly popular among content creators and marketers alike. Not only do longer blog posts tend to perform better in search engine rankings, but they also attract more organic traffic and engagement from readers. Here are some reasons why long-form content is beneficial for SEO. Comprehensive Coverage: Long-form blog posts allow you to thoroughly explore a topic and provide readers with comprehensive information. Search engines value content that is informative and authoritative, making long-form posts more likely to rank higher in SERPs. Keyword Optimization: Longer blog posts provide more opportunities for keyword optimization, allowing you to target a wider range of relevant keywords and phrases. This can help improve your search engine rankings and drive more organic traffic to your site. Backlink Opportunities: High-quality, long-form content is more likely to attract backlinks from other websites and publications. Backlinks are a key ranking factor for search engines, so earning links from authoritative sources can significantly boost your SEO efforts. Increased Dwell Time: Long-form content tends to keep readers engaged for longer periods, leading to increased dwell time on your site. Search engines interpret longer dwell times as a sign of quality and relevance, which can positively impact your search engine rankings. WriterAccess for High-Quality, Long-Form Content Creating high-quality, long-form content requires time, effort, and expertise. Fortunately, platforms like WriterAccess offer a convenient solution for businesses and marketers seeking professional content creation services. With a vast network of experienced writers and editors, WriterAccess makes it easy to find the perfect writer for your project and ensure that your content meets the highest standards of quality and relevance. Conclusion The ideal length of a blog post depends on a variety of factors, including the topic, the target audience, and the goals of the content creator. While there is no one-size-fits-all answer to the question of blog post length, following the guidelines outlined in this article can help you determine the optimal length for your content. Whether you're writing short, concise blog posts or in-depth, long-form articles, the key is to provide value to your readers and meet their needs effectively.
  6. eyword mapping plays a pivotal role in e-commerce SEO by ensuring that your website ranks well for relevant search queries. By mapping keywords to specific pages or sections of your website, you can optimize your content to align with user intent, thereby increasing the likelihood of attracting qualified traffic. Overview of How Keyword Clusters Can Improve Website Visibility and User Experience Keyword clusters, which group related search terms together, offer a powerful way to enhance both website visibility and user experience. By organizing keywords into coherent clusters, you can create a logical structure that not only appeals to search engines but also guides users seamlessly through your site. Strategies and Steps to Effectively Map Keywords for E-commerce Throughout this blog post, we will provide a detailed overview of the strategies and steps involved in effectively mapping keywords for e-commerce. From understanding the fundamentals of keyword mapping to optimizing product pages with targeted clusters, we will equip you with the knowledge and tools necessary to elevate your SEO game. Understanding Keyword Mapping in E-commerce Definition of Keyword Mapping: Keyword mapping involves assigning specific keywords to individual pages or sections of your website based on their relevance and search intent. By mapping keywords effectively, you can ensure that each page targets distinct search queries, maximizing your chances of ranking for a wide range of terms. Benefits of Keyword Clusters: Keyword clusters offer several benefits for e-commerce websites, including improved SEO performance, enhanced website structure, and higher conversion rates. By grouping related keywords together, you can create a cohesive content strategy that resonates with both search engines and users alike. Steps to Effectively Map Keywords and Clusters Conducting Keyword Research: Thorough keyword research forms the foundation of any successful keyword mapping strategy. By leveraging tools and techniques to identify relevant and high-performing keywords, you can gain valuable insights into the search behavior of your target audience. Grouping Keywords into Clusters: Once you have identified your target keywords, the next step is to group them into logical clusters based on their intent and relevance. This involves categorizing related keywords together to create cohesive themes that can be incorporated into your website content. Mapping Keywords to Website Structure: With your keyword clusters in hand, it's time to map them to your website structure in a way that maximizes their impact on SEO. This may involve optimizing your main navigation, creating dedicated landing pages, or incorporating keywords into your URL structure. Optimizing Product Pages with Keyword Clusters Product Titles and Descriptions: Product titles and descriptions provide valuable real estate for incorporating keyword clusters. By crafting compelling and descriptive copy that seamlessly integrates targeted keywords, you can improve both your search visibility and click-through rates. Image Alt Text and Metadata: In addition to textual content, optimizing your images with keyword-rich alt text and metadata can further enhance your SEO efforts. By associating relevant keywords with your images, you can improve their discoverability in image search results and enrich the overall user experience. Internal Linking Strategy: Internal linking plays a crucial role in guiding users through your website and distributing link equity effectively. By strategically linking product pages to relevant category pages with targeted anchor text, you can strengthen the thematic relevance of your content and improve your site's overall SEO performance. Creating SEO-Optimized Content Blogging and Content Marketing: Blogging offers a valuable opportunity to target specific keyword clusters and engage with your audience on a deeper level. By creating informative and engaging content around relevant topics, you can attract organic traffic and establish your authority in your niche. User-Generated Content Optimization: User-generated content, such as product reviews and testimonials, can also be leveraged for SEO purposes. By encouraging customers to use targeted keywords in their reviews and testimonials, you can enhance the visibility of your products and build trust with potential buyers. Monitoring and Refining Keyword Strategy Tracking Keyword Performance: Tracking the performance of your target keywords is essential for evaluating the effectiveness of your SEO efforts. By monitoring key metrics such as organic traffic and click-through rates, you can identify areas for improvement and refine your keyword strategy accordingly. Refining Strategy Based on Data: Data-driven decision-making is critical in the ever-evolving landscape of e-commerce SEO. By analyzing performance data and identifying underperforming keywords, you can iteratively refine your keyword strategy to stay ahead of the competition and adapt to changing trends. Conclusion Effective keyword mapping is a cornerstone of successful e-commerce SEO. By understanding the importance of keyword mapping, leveraging keyword clusters, and following best practices for optimization, you can improve your website's visibility, attract qualified traffic, and ultimately drive conversions. As you embark on your keyword mapping journey, remember to stay informed, stay agile, and above all, stay focused on the needs and preferences of your target audience. With this comprehensive guide, you now have the knowledge and tools necessary to master the art of keyword mapping and unlock the full potential of your e-commerce website. Happy mapping!
  7. O JavaScript é capaz de consultar o MySQL com a ajuda do PHP. Mas esse não é o caso do Laravel. A Gemini deu a dica de usar o Provider Service do Laravel ou fazer um API com o Laravel usando o recurso das rotas. Ao invés de seguir a orientação da Gemini, achei melhor apelar para a tentativa e erro. Já que eu não tenho um atalho entre o JavaScript e o Eloquent, eu pedi para o Eloquent jogar todo o banco de dados no HTML. Eu montei lista.blade.php assim: <input type="submit" value="{{$produto->codprod}}" onclick="alert({{$produto->prod}})"> Isso não deu certo, recebi a mensagem "missing (". Eu fiz uma nova tentativa, assim: <script> function show(codprod){ nome="c"+codprod controle=document.getElementById(nome) alert(controle.value) } </script> <table> @foreach($produtos as $produto) <tr><td><input type="submit" value="{{$produto->codprod}}" onclick="show({{$produto->codprod}})"> <input type=hidden id={{'c'.$produto->codprod}} value="{{$produto->prod}}"> @endforeach Veja que a gambiarra ficou enorme. O comando onclick=alert({{$produto->prod}}) não funciona, mas se for $produto->codprod funciona. A gambiarra é difícil de entender e se eu for tentar documentar isso, vai ficar pior. Ao invés de pedir para o JavaScript conversar com o Eloquent, eu pedi para o Eloquent jogar tudo no HTML, o problema é ajudar o JavaScript a encontrar o valor procurado no HTML através do id. Outra coisa que não dá para fazer é criar um id numérico, assim eu criei um prefixo "c" antes do código do produto. Bem mais simples é colocar todas as colunas no HTML. Isso não é problema para quem um monitor de 14 polegadas, mas um smartphone de 7 polegadas é bem complicado. Ao invés de eu colocar as colunas custo anterior e custo atual, eu só mudei a cor do total do item, ele fica vermelho se teve alteração no custo. Quando o usuário clica no item colorido, o JavaScript mostra o problema e pergunta se o usuário quer atualizar o custo.
  8. Impact of AI on Business Artificial Intelligence (AI) is a big deal in business. It's changing everything. AI helps companies work better, come up with new ideas, and talk to their customers. It's making a big difference in many parts of the business, like making things run smoother and improving how customers are helped. Increased Efficiency and Productivity AI tools are leading the way in making businesses work smarter and faster. They take over simple, everyday tasks, so people can do more important work. AI can analyze huge amounts of data really quickly and with great detail. AI-powered chatbots provide 24/7 customer service, helping businesses make smart choices and plan for the future. This boost in how well a business runs can save money and help it move faster, giving it an advantage over others. Enhanced Customer Experience AI is really changing how companies talk to their customers. It can suggest products you might like based on what you've bought before or looked at online. Also, AI chatbots can help customers any time of the day or night. This makes the shopping experience better for everyone. Companies can get to know their customers better, making them happier and more likely to keep coming back.
  9. One of the most effective ways to achieve these goals is through custom software development. By investing in tailored software solutions, businesses can streamline their operations, improve productivity, and position themselves for long-term growth. This blog explores the benefits of custom software and why On Wave Group stands out as a top choice for businesses looking to invest in their future. Tailored Solutions for Unique Needs Off-the-shelf software may offer basic functionality, but it often falls short when it comes to meeting the specific needs of a business. Custom software, on the other hand, is built from the ground up to address the unique challenges and requirements of each organization. Whether it's automating repetitive tasks, integrating disparate systems, or creating a seamless user experience, custom software can be tailored to fit like a glove, providing a competitive edge in today's dynamic market. Improved Efficiency and Productivity One of the key benefits of custom software is its ability to streamline processes and boost efficiency. By automating manual tasks and eliminating redundant processes, businesses can save time and resources, allowing employees to focus on more strategic activities. This not only improves productivity but also reduces the risk of errors, leading to better overall performance and customer satisfaction. Scalability and Flexibility As businesses grow and evolve, so do their software needs. Off-the-shelf solutions often struggle to keep pace with changing requirements, leading to costly and disruptive migrations. Custom software, on the other hand, is designed with scalability and flexibility in mind, allowing it to grow and adapt alongside the business. Whether it's adding new features, accommodating a larger user base, or integrating with new systems, custom software can easily scale to meet the evolving needs of a business. Enhanced Security and Data Protection With cyber threats on the rise, security is a top concern for businesses of all sizes. Custom software offers a higher level of security compared to off-the-shelf solutions, as it is built with security in mind from the outset. By implementing robust security measures such as encryption, access controls, and regular security updates, custom software helps protect sensitive data and mitigate the risk of breaches, providing peace of mind for businesses and their customers. Cost-Effectiveness in the Long Run While the upfront cost of custom software development may seem daunting, it often pays off in the long run. Unlike off-the-shelf solutions that require ongoing licensing fees and upgrades, custom software has lower maintenance costs and can provide a higher return on investment over time. By investing in a solution that is tailored to their needs, businesses can avoid the unnecessary expenses associated with off-the-shelf software and enjoy greater cost-effectiveness in the long term. On Wave Group: Your Partner for Custom Software Development When it comes to custom software development, On Wave Group stands out as a top choice for businesses looking to invest in their future. With years of experience and a proven track record of delivering innovative solutions, Onwave Group understands the unique challenges faced by businesses today and is committed to helping them succeed. Whether it's developing a custom ERP system, a mobile app, or a cloud-based solution, On Wave Group has the expertise and resources to deliver tailored software solutions that drive growth and success. Conclusion Custom software development offers a wide range of benefits for businesses looking to stay competitive in today's fast-paced market. From tailored solutions to improved efficiency and scalability, custom software provides a solid foundation for long-term growth and success. By partnering with a top software development company like Onwave Group, businesses can leverage the power of custom software to streamline their operations, boost productivity, and position themselves for success in the digital age.
  10. Última semana
  11. Gente, aqui não tenho impressora. Publicar em pdf dava errado, exportar em pdf dava errado, salvar como pdf dava errado. Deu certo mandando imprimir, visualizando impressão e imprimindo (sem impressora). Aí o corel é obrigado a salvar o pdf e dá certo.
  12. O seguinte código importa um arquivo xml, calcula o valor do produto como a soma do seu valor com o ICMS-ST, IPI e diferença de alíquota do ICMS, se houverem. Se ele não encontrar o código do produto correspondente ao do fornecedor, ele dispara um alerta 'Verificar'. Se houver diferença entre o custo anterior com o custo atual, ele avermelha o total do item, por onde o usuário pode atualizar o custo do produto, se assim desejar. Finalmente, o programa pede um número de lançamento para que ele possa encaminhar tudo para o banco de dados. Como esse programa é gratuito, não aceito reclamações. Mas se funcionar, eu aceito qualquer valor pelo pix frankhosaka@gmail.com. arquivo nota_bd.php <?php $mysqli=new mysqli("localhost","root","","diario"); if(isset($_POST['custoAtual'])){ $custoAtual=$_POST['custoAtual']; $codprod=$_POST['codprod']; $mysqli->query("update tbprod set custo=$custoAtual where codprod = $codprod"); } if(isset($_POST['lcto'])){ $lcto=$_POST['lcto']; $matriz=json_decode($_POST['matriz']); echo "aqui fica a rotina do lançamento $lcto que vai incluir os dados: "; var_dump($matriz); } arquivo notaDoFornecedor.php <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script> function atualizar(custoAtual,custoAnterior,codprod){ confirma=confirm("Atualizar?\ncusto atual: "+custoAtual+"\ncusto anterior: "+custoAnterior) if(confirma){ xmlhttp=new XMLHttpRequest() url = "nota_bd.php" formData = new FormData() formData.append('custoAtual',custoAtual) formData.append('codprod',codprod) xmlhttp.open("POST",url,true) xmlhttp.send(formData) location.reload() } } </script> <form method=post class="w-50 m-auto" enctype="multipart/form-data"> <label for=arquivo>Escolha o arquivo XML</label> <input type=file name=arquivo required> <input type=submit> </form> <?php if(!isset($_FILES['arquivo'])){exit;} $notaFornecedor=$_FILES['arquivo']['tmp_name']; function dec($value) { return ($value) ? number_format($value,2,',','.') : null; } $mysqli=new mysqli("localhost","root","","diario"); // Carregar o arquivo XML $dom = new DOMDocument(); $dom->load($notaFornecedor); // Acessar os itens $nfe = $dom->documentElement; $itens = $nfe->getElementsByTagName('det'); // Calcula diferença de alíquota do ICMS $difAliqICMS=0; $aliquotaInterna=0.18; foreach($itens as $item){ if($item->getElementsByTagName('CFOP')->item(0)->textContent==6102){ $vBC=$item->getElementsByTagName('vBC')->item(0)->textContent; $vICMS=$item->getElementsByTagName('vICMS')->item(0)->textContent; $difAliqICMS += intval(($vBC*$aliquotaInterna - $vICMS)*100)/100; } } echo "<table class='table table-striped table-sm w-50 m-auto'>"; $vNF=$nfe->getElementsByTagName('vNF')->item(0)->textContent; $nNF=$nfe->getElementsByTagName('nNF')->item(0)->textContent; $xNome=$nfe->getElementsByTagName('xNome')->item(0)->textContent; echo "<tr class=fw-semibold><td><td><td>NF $nNF ". substr($xNome,0,4). "<td><td class=text-end>". dec($vNF); if($difAliqICMS!==0){ echo "<tr class=fw-semibold><td><td><td>Diferença de Alíquota de ICMS<td><td class=text-end>" .dec($difAliqICMS); echo "<tr class=fw-semibold><td><td><td>Total a conferir<td><td class=text-end>" .dec($difAliqICMS+$vNF); } echo "<tr class=fw-semibold><td>CodForn<td>CodProd<td>Produto<td>Qt<td class=text-end>Total"; $soma=0; $matriz=[]; foreach ($itens as $item) { // no campo codforn uso a primeira letra para identificar o fornecedor $codforn = $xNome[0] . $item->getElementsByTagName('cProd')->item(0)->textContent; $consulta=$mysqli->query("select codprod from tbprod where codforn like '%$codforn%' "); $codprod='<spam class=text-danger>Verificar</spam>'; if ($consulta->num_rows==1) { $codprod=$consulta->fetch_assoc()['codprod']; } $produto = $item->getElementsByTagName('xProd')->item(0)->textContent; $quantidade=$item->getElementsByTagName('qCom')->item(0)->textContent; if(is_numeric($codprod)){ $produtoDobrado = [510]; if(in_array($codprod,$produtoDobrado)){ $quantidade = 2 * $quantidade; } } $vICMSST = ($item->getElementsByTagName('vICMSST')->item(0)) ? $item->getElementsByTagName('vICMSST')->item(0)->textContent : null; $difAliqICMS=0; if($item->getElementsByTagName('CFOP')->item(0)->textContent==6102){ $vBC=$item->getElementsByTagName('vBC')->item(0)->textContent; $vICMS=$item->getElementsByTagName('vICMS')->item(0)->textContent; $difAliqICMS = intval(($vBC*$aliquotaInterna - $vICMS)*100)/100; } $vIPI=0; if($item->getElementsByTagName('vIPI')->item(0)){ $vIPI=$item->getElementsByTagName('vIPI')->item(0)->textContent; } $vProd = $item->getElementsByTagName('vProd')->item(0)->textContent; $valorTotal=$vProd+$vICMSST+$difAliqICMS+$vIPI; $soma += $valorTotal; $class="class='text-end'"; if(is_numeric($codprod)){ $custoAtual=intval($valorTotal/$quantidade*100)/100; $consulta=$mysqli->query("select custo from tbprod where codprod=$codprod"); $custoAnterior=$consulta->fetch_assoc()['custo']; if(abs($custoAnterior-$custoAtual)>0.02){ $class="class='text-end text-danger' onclick='atualizar($custoAtual,$custoAnterior,$codprod)'"; } } echo "<tr><td>" . $codforn; echo "<td>" . $codprod; echo "<td>" . substr($produto,0,25); echo "<td>" . intval($quantidade); echo "<td $class>" . dec($valorTotal); $matriz[]=['codpprod'=>$codprod,'qt'=>$quantidade,'subtotal'=>$valorTotal]; } ?> <tr class=fw-semibold><td><td><td>Total dos itens<td><td class=text-end><?=dec($soma)?> </table> <div class="w-50 m-auto"> Enviar tudo para o banco de dados <form action=nota_bd method=post> <input name=lcto placeholder="Número do Lançamento" required> <input type=hidden name=matriz value=<?=json_encode($matriz)?>> <input type=submit> </form> </div>
  13. exercicio proposto utilizando a estrutura enquanto 1) Foi realizada uma pesquisa sobre algumas características físicas da população de uma certa região, a qual coletou os seguintes dados referentes a cada habitante, para análise: · Nome · Sexo (“M” – Masculino e “F” – Feminino) · Cor dos olhos (“A” – Azuis, “V” – Verde ou “C” – Castanho) · Idade · Altura Desenvolva um programa que determine e escreva: a) A quantidade de pessoas do sexo feminino cuja idade seja acima de 15 anos inclusive, tenha altura acima de 1,50 e olhos castanhos; b) A quantidade de pessoas do sexo masculino cuja idade seja acima de 17 anos inclusive, tenha altura acima de 1,70 e olhos azuis; c) A média das idades das mulheres lidas; d) A média das alturas dos homens lidos; e) A média de todas as idades lidas; f) A média de todas as alturas lidas. Obs.: A última pessoa que não entrará no cálculo, terá seu nome igual a FIM (flag).
  14. Hoje o pessoal da contabilidade me pediu as notas fiscais que foram emitidas em abril. Eu fui na Bling, baixei o arquivo e mandei para a contabilidade. A seguir, eles me mandaram uma lista de notas fiscais que estavam faltando no arquivo, eu fui verificar, e eu vi que eram notas que não foram autorizadas pela Secretaria da Fazenda. Eu achei bacana o trabalho da contabilidade, e fiquei imaginando como fazer isso no PHP. Estudei os arquivos XML e eu vi que o número da NF está na posição 29,30,31,32,33,34 daquele monte de número que aparece no nome do arquivo, e assim eu montei o meu código PHP com a ajuda da Gemini: arquivo index.php <?php $diretorio = 'xml'; $contaArquivos = count(scandir($diretorio)) - 2; echo "Número de arquivos xml: $contaArquivos <br>"; $notasFiscais = []; $nfces = scandir('xml'); foreach($nfces as $nfce){ if($nfce !== '.' && $nfce !=='..' ){ $notasFiscais[]=intval(substr($nfce,28,6)); } } sort($notasFiscais); $primeiraNota=intval($notasFiscais[0]); $ultimaNota=intval($notasFiscais[$contaArquivos-1]); echo "primeira nota: $primeiraNota <br>"; echo "ultima nota: $ultimaNota <br>"; echo "notas faltantes: " . ($ultimaNota-$primeiraNota+1-$contaArquivos) . "<br>"; for($i=$primeiraNota;$i<=$ultimaNota;$i++){ if(!in_array($i,$notasFiscais)){ echo $i . "<br>"; } }
  15. Existem muitos consoles no mercado. Estou procurando o cassino móvel Vera&John perfeito para o meu jogo
  16. Mais Cedo
  17. Pessoal, preciso saber em tempo real quantos usuários estão conectados no sistema PHP. Utilizo LDAP do AD como autenticação para acesso, alguém tem uma luz? Autentico pelo LDAP mas carrego um perfil ( tabela) mssql para saber as permissões do usuário.
  18. qual sistema operacional esta usando? pip esta instalado? esta usando alguma ide para instalar módulos, ou esta usando terminal?
  19. não consigo usar o comando pip segui alguns tutorias e percebi que minha pasta scripts do python estava vazia oque fazer
  20. Fiz uma macro para que quando um valor da coluna C estiver duplicado, recortar e colar a linha em outra aba. No entanto ele recortar apenas 1 das linhas duplicadas e eu preciso que recorte todas. Por exemplo, na Coluna C o valor X aparece 3x, eu quero que as três linhas com esse valor sejam recortadas e coladas na outra aba, não somente 1 linha, como está acontecendo. Abaixo segue meu código, desde já agradeço pela ajuda: Sub CopiarDados() Dim intTabela As Range Dim i As Integer, totalLin As Integer, nLin As Integer Dim n As Integer Set intTabela = Planilha2.Range("A1").CurrentRegion totalLin = intTabela.Rows.Count For i = 2 To totalLin n = WorksheetFunction.CountIf(intTabela.Columns(3), intTabela.Cells(i, 3)) If n > 1 Then nLin = Planilha6.Range("A1").CurrentRegion.Rows.Count + 1 intTabela.Rows(i).Cut Planilha6.Cells(nLin, 1) End If Next Application.CutCopyMode = False Sheets("Planilha6").Select End Sub
  21. Boa tarde estou desenvolvendo uma Web api, tenho uma função que e usada para tranferir produto de uma mesa para outra mesa. Quando solicito a transferencia o produto que foi solicitado a transferencia e deletado, o mais estranho que a função finaliza o update com o commit. Veja a função. public List<TransfereItensMesaMesa> TransfereItenMesaMesa(long OpOr, long MesaOr, long MesaDest, long Codigo, long CodProduto, double Quantidade, long CodCaixa, DateTime DataCaixa, long CodUsuario) { List<TransfereItensMesaMesa> _Estorna = new List<TransfereItensMesaMesa>(); bool Retorno = false; NpgsqlTransaction Trans; NpgsqlConnection Cnx = new NpgsqlConnection(Variaveis.StringConexaoPG); Cnx.Open(); Trans = Cnx.BeginTransaction(); try { var StatusOr = ffuncaobd.RetDadosString("Select \"Status\" From \"MesaOP\" Where \"Fechada\"='N' And \"Codigo\"=" + OpOr + " And \"Estorno\"='N' And \"Impressa\"='N' Order by \"Codigo\" Desc LIMIT 1"); if (StatusOr.ToUpper() != "Impressa".ToUpper()) { if (ffuncaobd.RetDados("Select \"Codigo\",\"DataAbertura\",\"Status\" From \"MesaOP\" Where \"Fechada\"='N' And \"Mesa\"=" + MesaDest + " And \"Estorno\"='N' Order by \"Codigo\" Desc LIMIT 1" , new string[] { "Codigo", "DataAbertura", "Status" }, 3) == true) { if (Variaveis.Dados is Array) { if (Variaveis.Dados is null) { } else { if (ffuncao.IsNumeric(Variaveis.Dados[0]) == true) { CodigoVenda = Convert.ToInt64(Variaveis.Dados[0]); Status = Variaveis.Dados[2].ToString(); if (Status.ToUpper() == "Impressa".ToUpper()) { Variaveis.Mensage = "A mesa de destino já foi impressa, para tranferir um item debloqueie a mesa"; Retorno = false; Trans.Rollback(); Cnx.Close(); goto Sair; } } } } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao caregar a mesa de destino"; Retorno = false; goto Sair; } if (CodigoVenda == 0) { if (ffuncaobd.GravaTrans_Novo(Cnx, Trans, "Insert Into \"MesaOP\" " , new string[] { "Mesa", "DataCaixa", "Usuario", "Caixa", "DataAbertura" } , new string[] { MesaDest.ToString(), DataCaixa.ToString(), CodUsuario.ToString(), CodCaixa.ToString(), DateTime.Now.ToString() } , new string[] { "bi", "d", "bi", "bi", "DT" }) == true) { if (ffuncaobd.RetDadosTrans_Novo(Cnx, Trans, "Select \"Codigo\",\"DataAbertura\",\"Status\" From \"MesaOP\" Where \"Fechada\"='N' And \"Mesa\"=" + MesaDest + " And \"Estorno\"='N' Order by \"Codigo\" Desc LIMIT 1" , new string[] { "Codigo", "DataAbertura", "Status" }, 3) == true) { if (Variaveis.Dados is Array) { if (Variaveis.Dados is null) { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao caregar a mesa"; Retorno = false; goto Sair; } else { if (ffuncao.IsNumeric(Variaveis.Dados[0]) == true) { CodigoVenda = Convert.ToInt64(Variaveis.Dados[0]); Status = Variaveis.Dados[2].ToString(); } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao caregar a mesa"; Retorno = false; goto Sair; } } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao caregar a mesa"; Retorno = false; goto Sair; } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao caregar a mesa"; Retorno = false; goto Sair; } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Erro ao cadastrar a mesa, para recebar a transferencia"; Retorno = false; goto Sair; } } if (CodigoVenda > 0) { string Sql = "UpDate \"MesaDetalhe\" Set \"Operacao\"=" + CodigoVenda + " Where \"Codigo\"=" + Codigo + ";"; if (ffuncaobd.GravaTrans_Novo_RetAfect(Cnx, Trans, "UpDate \"MesaDetalhe\" Set " , new string[] { "Operacao" } , new string[] { CodigoVenda.ToString() } , new string[] { "bi" } , Codigo , new string[] { "Codigo" } , new string[] { Codigo.ToString() } , false) > 0) //if (ffuncaobd.DeletarNovoTrans_RetNUmero_Novo(Cnx, Trans, Sql, false) > 0) { if (ffuncaobd.RetDadosNumeroInt64Trans_Novo(Cnx, Trans, "Select count(*) From \"MesaDetalhe\" where \"Operacao\"=" + OpOr) == 0) { string SqlOp = "Delete from \"MesaOP\" Where \"Codigo\"=" + OpOr + ";"; if (ffuncaobd.DeletarNovoTrans_RetNUmero_Novo(Cnx, Trans, SqlOp, false) > 0) { Trans.Commit(); Cnx.Close(); Variaveis.Mensage = "Tranferencia Realizada com Sucesso!!!"; Retorno = true; } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Não foi possível tranferir o item selecionado, Deletar a Mesa de Origem Sem Produtos"; Retorno = false; goto Sair; } } else { Trans.Commit(); Cnx.Close(); Variaveis.Mensage = "Tranferencia Realizada com Sucesso!!!"; Retorno = true; } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Não foi possível tranferir o item selecionado para a mesa de destino"; Retorno = false; goto Sair; } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "Não foi possível carregar a operação da mesa de destino"; Retorno = false; goto Sair; } } else { Trans.Rollback(); Cnx.Close(); Variaveis.Mensage = "A mesa de origem já foi impressa, para tranferir um item debloqueie a mesa"; } } catch (Exception ex) { Variaveis.Erros = ex.Message; Variaveis.Mensage = "Não foi possivel Transfere o Iten da Mesa " + ex.Message; try { Trans.Rollback(); Cnx.Close(); } catch { try { Cnx.Close(); } catch { } } } Sair: _Estorna.Add(new TransfereItensMesaMesa() { Op = OpOr, Codigo = Codigo, CodProduto = CodProduto, Quantidade = Quantidade, CodCaixa = CodCaixa, DataCaixa = DataCaixa, CodUsuario = CodUsuario, Menssagem = Variaveis.Mensage, Erro = Variaveis.Erros, Retorno = Retorno }); Variaveis.Erros = ""; Variaveis.Mensage = ""; return _Estorna; } Obs: O registro e deletado somente quando na tabela mao o registro e criado junto com a alteração(UpDate) Se o restro na tabela mao já existe faz tudo certinho.
  22. Bom dia Pessoal! Preciso muito da ajuda de vocês. Estou criando um relatório no Crystal Reports, e o meu problema é que preciso que o cabeçalho não aparece na proxima página, só que sestá acontencedo é que, quando eu imprimo o relatório a primeira página aparece 1 de 1 e na segunda página aparece 1 de 4 aí o cabeçalho aparece duas vezes. Como faço para deixar a contagem de página certa, 1 de 5 e o cabeçalho aparecer só na primeira?
  23. Alguém poderia me ajudar nesta situação?
  24. Angela, para criar um projeto .NET Core no Visual Studio 2019 ou 2022, você precisa ter instalado o workload ".NET Core cross-platform development". Você pode verificar isso no Visual Studio Installer, na seção " fortune tiger". Se essa workload não estiver instalada, você pode adicioná-la e, em seguida, reiniciar o Visual Studio para que as alterações tenham efeito. Após isso, você deve conseguir criar projetos .NET Core normalmente.
  25. Este código VBA parece ser utilizado para automatizar tarefas no SAP usando o SAP GUI Scripting. Ele inicia o aplicativo SAP, espera alguns segundos para que ele abra completamente, e então realiza uma série de ações, como redimensionar a janela, inserir uma transação, e pressionar botões no fortune tiger. É importante ter cuidado ao usar automações desse tipo, pois podem violar políticas de segurança ou termos de serviço da empresa. Certifique-se de ter permissão para automatizar essas tarefas e de seguir as diretrizes da sua organização.
  26. Olá a todos. O https://f12bet-entrar.com/ é o lugar perfeito para quem está procurando uma casa de apostas confiável. Estou jogando nesse site há alguns meses e sempre recebo apenas impressões positivas. Sua interface é muito intuitiva, o que é especialmente importante para iniciantes. Além disso, a variedade de eventos esportivos e as altas probabilidades tornam o jogo ainda mais emocionante. Fiquei especialmente satisfeito com o suporte ao cliente rápido e eficiente - todos os problemas são resolvidos instantaneamente. Eu recomendo!
  27. Na base da tentativa e erro, estudei o motor XMLhttpRequest do Javascript para conectar o HTML com o PHP bem como carregar um outro HTML dentro de um arquivo HTML. Para testar o código tive que limpar o histórico do navegador e até fechar o navegador. arquivo /Astudy/config.php <?php session_start(); define('DBNAME','teste'); define('HOST','localhost'); define('USER','root'); define('PASSWORD',''); $dbname=DBNAME; $verEsquema="select * from sys.schema_table_statistics where table_schema='$dbname'"; $pdoTemp=new PDO('mysql:host='.HOST,USER,PASSWORD); $resultado=$pdoTemp->query($verEsquema); $dbExiste=$resultado->fetchColumn()===$dbname; if(!$dbExiste){ $pdo->exec("create database ".DBNAME); $pdo->exec("use ".DBNAME); $pdo->exec("CREATE TABLE `usuarios` (`id` bigint unsigned NOT NULL AUTO_INCREMENT, `nome` varchar(45) ,`email` varchar(45) ,`senha` varchar(255), PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1"); $nome="Frank K Hosaka"; $email='frankhosaka@gmail.com'; $senha='1234'; $hashSenha=password_hash($senha,PASSWORD_BCRYPT); $pdo->query("insert into usuarios (nome,email,senha) values ('$nome','$email','$hashSenha')"); } $pdo=new PDO('mysql:host='.HOST.';dbname='.DBNAME,USER,PASSWORD); if(isset($_POST['email'])){ $email=$_POST['email']; $senha=$_POST['senha']; $smt=$pdo->query("select * from usuarios where email='$email'"); $usuario=$smt->fetchAll(PDO::FETCH_OBJ); if(count($usuario)==0){ echo "não existe usuario com email $email";exit; } if(password_verify($senha,$usuario[0]->senha)){ $_SESSION['id']=$usuario[0]->id; $_SESSION['nome']=$usuario[0]->nome; echo "liberado"; } else { echo "senha incorreta"; } } if(isset($_POST['usuario'])){ $id=$_SESSION['id']; $nome=$_SESSION['nome']; echo json_encode(['nome'=>$nome,'id'=>$id]); } arquivo /Astudy/diario.html <!DOCTYPE html> <meta charset="utf-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <script src="java.js"></script> <script>usuario()</script> <body style="max-width:500px;margin:0 auto"> <script src="java.js"></script> <script>carregaHTML('menu.html')</script> <div id="conteudo"></div> <table class="table table-striped table-sm"> <tr class=fw-semibold><td>data<td>contaD<td>contaC<td>Valor<td>Histórico <tr><td>01/05/24<td>101<td>301<td>15,00<td>Salário </table> arquivo /Astudy/index.html <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="java.js"></script> <body class="bg-light w-25 m-auto"> <main class="w-100" style="margin-top:120px"> <form action="javascript:login()" id="formLogin"> <div class="form-floating"> <input name="email" value="frankhosaka@gmail.com" class="form-control"> <label>Email</label> </div> <div class="form-floating"> <input type="password" name="senha" value="1234" class="form-control"> <label>Senha</label> <div> <input type="submit" class="w-100 btn btn-lg btn-primary"> </form> </main> </body> arquivo /Astudy/java.js function carregaHTML(url) { xhr = new XMLHttpRequest() xhr.open('GET', url) xhr.onload = function() { if (xhr.status === 200) { htmlContent = xhr.responseText; conteudo.innerHTML = htmlContent; } } xhr.send(); } function login(){ xhr = new XMLHttpRequest() formData=new FormData(formLogin) xhr.open('POST','config.php') xhr.onload = function() { if(xhr.status===200){ if(xhr.responseText=='liberado'){ window.location.href="menu.html"; } else { alert(xhr.responseText) } } } xhr.send(formData) } function usuario(){ xmlhttp=new XMLHttpRequest(); url = "config.php"; formData = new FormData(); formData.append('usuario',''); xmlhttp.open("POST",url,true); xmlhttp.send(formData); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ usuario=JSON.parse(xmlhttp.responseText) nomeUsuario.innerHTML=usuario.nome if(usuario.id==1){ usuario1.classList.remove('d-none') usuario1.classList.add('d-block') } } } } arquivo /Astudy/menu.html <!DOCTYPE html> <meta charset="utf-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <script src="java.js"></script> <script>usuario()</script> <body style="max-width:500px;margin:0 auto"> <header id=cabecalho class="navbar navbar-light sticky-top bg-light flex-md-nowrap p-0"> Projeto HTML <div class=dropdown> <button type=button class="btn btn-outline-primary dropdown-toggle" data-bs-toggle=dropdown id=btmenu> Menu </button> <ul class="dropdown-menu" > <div id="usuario1" class="d-none"> <li><a class=dropdown-item href='diario.html' >Diário</a></li> <li><a class=dropdown-item href='balancete.html'>Balancete</a></li> <li><a class=dropdown-item href='pagar.html'>Pagar</a></li> <li><a class=dropdown-item href='outros.html'>Outros</a></li> </div> <li><a class=dropdown-item href='orcamento.html'>Orcamento</a></li> <li><a class=dropdown-item href='pessoas.html'>Pessoa</a></li> <li><a class=dropdown-item href='produtos.html'>Produto</a></li> <li><a class=dropdown-item href='venda.html'>Relatório de Venda</a></li> <li><a class=dropdown-item href='mercado.html'>Mercado Pago</a></li> </ul> </div> <div class="dropdown"> <button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> <spam id="nomeUsuario"></spam> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="index.html">Sair</a></li> <li><a class="dropdown-item" href="alterarSenha.html">Mudar a senha</a></li> </ul> </div> </header>
  28. Frank K Hosaka

    menu.html

    Consegui carregar um arquivo html dentro de outro arquivo html com a ajuda do JavaScript. Praticamente o código do menu.html vai ser o código padrão de todos os outros arquivos html. Para testar esses códigos, eu tive que limpar o histórico do navegador, fechar o navegador, abrir o navegador, e depois testar o código. Como o código menu.html precisa de duas funções do JavaScript, decidi colocar todas as funções do JavaScript num só arquivo que chamei de java.js: arquivo /HTML/basicoMenu.html <header id=cabecalho class="navbar navbar-light sticky-top bg-light flex-md-nowrap p-0"> Projeto HTML <div class=dropdown> <button type=button class="btn btn-outline-primary dropdown-toggle" data-bs-toggle=dropdown id=btmenu> Menu </button> <ul class="dropdown-menu" > <div id="usuario1" class="d-none"> <li><a class=dropdown-item href='diario.html' >Diário</a></li> <li><a class=dropdown-item href='balancete.html'>Balancete</a></li> <li><a class=dropdown-item href='pagar.html'>Pagar</a></li> <li><a class=dropdown-item href='outros.html'>Outros</a></li> </div> <li><a class=dropdown-item href='orcamento.html'>Orcamento</a></li> <li><a class=dropdown-item href='pessoas.html'>Pessoa</a></li> <li><a class=dropdown-item href='produtos.html'>Produto</a></li> <li><a class=dropdown-item href='venda.html'>Relatório de Venda</a></li> <li><a class=dropdown-item href='mercado.html'>Mercado Pago</a></li> </ul> </div> <div class="dropdown"> <button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> <spam id="nomeUsuario"></spam> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="index.php">Sair</a></li> <li><a class="dropdown-item" href="alterarSenha.html">Mudar a senha</a></li> </ul> </div> </header> arquivo /HTML/config.php <?php session_start(); $mysqli=new mysqli("localhost","root","","diario"); if(isset($_POST['email'])) { $email=$_POST['email']; $senha=$_POST['senha']; $query=$mysqli->query("select * from tbusuario where email='$email'"); $usuario=$query->fetch_assoc(); $validaEmail=$usuario['email']; if(!$validaEmail) { echo "Dados inválidos"; exit; } $confirmar=$usuario['password']; $validaSenha=password_verify($senha,$confirmar); if(!$validaSenha) { echo "Dados inválidos!"; exit; } $_SESSION['id']=$usuario['id']; $_SESSION['nome']=$usuario['name']; echo "liberado"; } if(isset($_POST['usuario'])){ $nome=$_SESSION['nome']; $id=$_SESSION['id']; echo json_encode(['nome'=>$nome,'id'=>$id]); } arquivo /HTML/index.html <!DOCTYPE html> <html lang="en"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <title>Projeto HTML</title> <script src="java.js"></script> <body class="d-flex text-center bg-light"> <main class="w-25 m-auto" style="padding-top:160px"> <form id="formLogin" action="javascript:void(0)"> <h1 class="h3 mb-3 fw-normal">Projeto HTML</h1> <div id="mensagem"></div> <div class="form-floating"> <input type="email" class="form-control" name=email id=email autofocus required> <label for="floatingInput">Email</label> </div> <div class="form-floating"> <input type="password" class="form-control" name="senha" id="senha" required ondblclick="senha.type='text'"> <label for="floatingPassword">Duplo click para ver a Senha<label> </div> <input class="w-100 btn btn-lg btn-primary" type="submit" value="Entrar" onclick="login()"> </form> </main></body> arquivo /HTML/java.js function carregarBasicoMenu(){ xhr = new XMLHttpRequest(); externalHTMLURL = 'basicoMenu.html'; xhr.open('GET', externalHTMLURL); xhr.onload = function() { if (xhr.status === 200) { externalHTML = xhr.responseText; menu.innerHTML = externalHTML; } else { console.error('Error loading external HTML:', xhr.statusText); } } xhr.send(); } function login() { xmlhttp=new XMLHttpRequest(); url = "config.php"; formData = new FormData(document.getElementById("formLogin")); xmlhttp.open("POST",url,true); xmlhttp.send(formData); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ if(xmlhttp.responseText=="liberado"){ window.location.href="menu.html" } mensagem.innerHTML=xmlhttp.responseText; } } } function usuario () { // pega o id e nome do usuário no php e amplia o menu de opções se o usuario = 1 xmlhttp=new XMLHttpRequest(); url = "config.php"; formData = new FormData(); formData.append('usuario',''); xmlhttp.open("POST",url,true); xmlhttp.send(formData); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ usuario=JSON.parse(xmlhttp.responseText) nomeUsuario.innerHTML=usuario.nome if(usuario.id==1){ usuario1.classList.remove('d-none') usuario1.classList.add('d-block') } } } } arquivo /HTML/menu.html <!DOCTYPE html> <html lang="en"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <style> a {color:blue;text-decoration:none} a:hover {color:black;} form {margin:0} .linha {line-height:0px} summary{list-style:none} td {white-space: nowrap} </style> <title>Projeto HTML</title> <body class="text-center bg-light w-25 m-auto"> <script src="java.js"></script> <script>carregarBasicoMenu();usuario()</script> <div id="menu"></div>
  29. Frank K Hosaka

    menu.html

    Usando o método da tentativa e erro, bem como a ajuda da Gemini, consegui montar o meu segundo arquivo html. Eu fiquei surpreso por ele ter funcionado, o código JavaScript funcionou, mesmo que tenha sido colocado no topo da página. Desconfio que o JavaScript conseguiu encontrar o <div id=usuario1> bem como <spam id=nomeUsuario> graças ao marcador <!DOCTYPE html>. Agora o meu desafio é reutilizar esse mesmo código em várias páginas que virão adiante, eu não consegui utilizar o marcador <include> do HTML, assim vou usar o motor xmlhttp do JavaScript. Espero que dê certo. arquivo menu.html <!DOCTYPE html> <html lang="en"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <style> a {color:blue;text-decoration:none} a:hover {color:black;} body {align-items: center;background-color: #f5f5f5;} form {margin:0} .linha {line-height:0px} summary{list-style:none} td {white-space: nowrap} </style> <title>Projeto HTML</title> <script> // pega o id e nome do usuário no php e amplia o menu de opções se o usuario = 1 xmlhttp=new XMLHttpRequest(); url = "config.php"; formData = new FormData(); formData.append('usuario',''); xmlhttp.open("POST",url,true); xmlhttp.send(formData); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ usuario=JSON.parse(xmlhttp.responseText) nomeUsuario.innerHTML=usuario.nome if(usuario.id==1){ usuario1.classList.remove('d-none') usuario1.classList.add('d-block') } } } </script> <body style="max-width:500px;margin:0 auto"> <header id=cabecalho class="navbar navbar-light sticky-top bg-light flex-md-nowrap p-0"> Projeto HTML <div class=dropdown> <button type=button class="btn btn-outline-primary dropdown-toggle" data-bs-toggle=dropdown id=btmenu> Menu </button> <ul class="dropdown-menu" > <div id="usuario1" class="d-none"> <li><a class=dropdown-item href='diario.html' >Diário</a></li> <li><a class=dropdown-item href='balancete.html'>Balancete</a></li> <li><a class=dropdown-item href='pagar.html'>Pagar</a></li> <li><a class=dropdown-item href='outros.html'>Outros</a></li> </div> <li><a class=dropdown-item href='orcamento.html'>Orcamento</a></li> <li><a class=dropdown-item href='pessoas.html'>Pessoa</a></li> <li><a class=dropdown-item href='produtos.html'>Produto</a></li> <li><a class=dropdown-item href='venda.html'>Relatório de Venda</a></li> <li><a class=dropdown-item href='mercado.html'>Mercado Pago</a></li> </ul> </div> <div class="dropdown"> <button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> <spam id="nomeUsuario"></spam> </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="?ControleLogin.sair">Sair</a></li> <li><a class="dropdown-item" href="?ControleLogin.alterarsenha">Mudar a senha</a></li> </ul> </div> </header> arquivo config.php <?php // ... if(isset($_POST['usuario'])){ $nome=$_SESSION['nome']; $id=$_SESSION['id']; echo json_encode(['nome'=>$nome,'id'=>$id]); }
  1. Mais Resultados


  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...